【发布时间】:2020-03-05 13:36:43
【问题描述】:
我需要使用 sec.axis 创建一个双 y 图,但无法正确缩放两个轴。
我一直在遵循此线程中的说明:ggplot with 2 y axes on each side and different scales
但每次我将 ylim.prim 中的下限更改为 0 以外的任何值时,都会弄乱整个情节。出于可视化原因,我需要两个轴的非常具体的 y 限制。另外,当我将 geom_col 更改为 geom_line 时,它也会弄乱辅助轴的限制。
climate <- tibble(
Month = 1:12,
Temp = c(23,23,24,24,24,23,23,23,23,23,23,23),
Precip = c(101,105,100,101,102, 112, 101, 121, 107, 114, 108, 120)
)
ylim.prim <- c(0, 125) # in this example, precipitation
ylim.sec <- c(15, 30) # in this example, temperature
b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])
ggplot(climate, aes(Month, Precip)) +
geom_col() +
geom_line(aes(y = a + Temp*b), color = "red") +
scale_y_continuous("Precipitation", sec.axis = sec_axis(~ (. - a)/b, name = "Temperature"),) +
scale_x_continuous("Month", breaks = 1:12)
ylim.prim <- c(0, 125) # in this example, precipitation
ylim.sec <- c(15, 30) # in this example, temperature
b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])
ggplot(climate, aes(Month, Precip)) +
geom_line() +
geom_line(aes(y = a + Temp*b), color = "red") +
scale_y_continuous("Precipitation", sec.axis = sec_axis(~ (. - a)/b, name = "Temperature"),) +
scale_x_continuous("Month", breaks = 1:12)
ylim.prim <- c(95, 125) # in this example, precipitation
ylim.sec <- c(15, 30) # in this example, temperature
b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])
ggplot(climate, aes(Month, Precip)) +
geom_line() +
geom_line(aes(y = a + Temp*b), color = "red") +
scale_y_continuous("Precipitation", sec.axis = sec_axis(~ (. - a)/b, name = "Temperature"),) +
scale_x_continuous("Month", breaks = 1:12)
【问题讨论】:
-
我认为
a的等式应该是ylim.prim[1] - b*ylim.sec[1]。如果我使用它而不是您的定义,则两个比例之间的重新映射似乎有效,并且两个轴的限制与您的定义相匹配。