facet_wrap을 사용하는 동안 ggplot2에서 여러 패널을 플롯하려고합니다. 두 개의 y 축을 갖고 싶습니다. 왼쪽 y 축 범위는 5 ~ 27이고 오른쪽 y 축 범위는 25 ~ 27입니다. 회귀선으로 모든 데이터 포인트를 표시하고 싶습니다. 그러나 플로팅 할 때 오른쪽 y 축의 변동이 다른 데이터 세트에 비해 낮으므로 평평한 선으로 나타납니다. 데이터의 변동이 명확하게 보이도록 오른쪽 y 축을 25에서 27로 유지하고 싶습니다. 이 코드 1을 사용 했지만 분류 할 수 없습니다. 어떤 도움이라도 대단히 감사합니다.
library(ggplot2)
scaleFactor <- max(d1$weeks) / max(d1$income)
ggplot(mtcars, aes(x=Year)) +
geom_smooth(aes(y=weeks), method="loess", col="blue") +
geom_smooth(aes(y=income * scaleFactor), method="loess", col="red") +
scale_y_continuous(name="weeks", sec.axis=sec_axis(~./scaleFactor, name="income")) +
theme(
axis.title.y.left=element_text(color="blue"),
axis.text.y.left=element_text(color="blue"),
axis.title.y.right=element_text(color="red"),
axis.text.y.right=element_text(color="red")
)
최대 값을 다시 조정하는 대신 데이터 범위를 겹치게 만드는 경우 다음을 시도 할 수 있습니다.
먼저 작업을 더 쉽게하기 위해 함수 팩토리를 만들 것입니다.
library(ggplot2)
library(scales)
#> Warning: package 'scales' was built under R version 4.0.3
# Function factory for secondary axis transforms
train_sec <- function(from, to) {
from <- range(from)
to <- range(to)
# Forward transform for the data
forward <- function(x) {
rescale(x, from = from, to = to)
}
# Reverse transform for the secondary axis
reverse <- function(x) {
rescale(x, from = to, to = from)
}
list(fwd = forward, rev = reverse)
}
그런 다음 함수 팩토리를 사용하여 데이터 및 보조 축에 대한 변환 함수를 만들 수 있습니다.
# Learn the `from` and `to` parameters
sec <- train_sec(mtcars$hp, mtcars$cyl)
다음과 같이 신청할 수 있습니다.
ggplot(mtcars, aes(x=disp)) +
geom_smooth(aes(y=cyl), method="loess", col="blue") +
geom_smooth(aes(y= sec$fwd(hp)), method="loess", col="red") +
scale_y_continuous(name="cyl", sec.axis=sec_axis(~sec$rev(.), name="hp")) +
theme(
axis.title.y.left=element_text(color="blue"),
axis.text.y.left=element_text(color="blue"),
axis.title.y.right=element_text(color="red"),
axis.text.y.right=element_text(color="red")
)
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'
다음은 다른 데이터 세트를 사용한 예입니다.
sec <- train_sec(economics$psavert, economics$unemploy)
ggplot(economics, aes(date)) +
geom_line(aes(y = unemploy), colour = "blue") +
geom_line(aes(y = sec$fwd(psavert)), colour = "red") +
scale_y_continuous(sec.axis = sec_axis(~sec$rev(.), name = "psavert"))
reprex 패키지 (v1.0.0)에 의해 2021-02-04에 생성됨
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다