如何在具有不同y范围的ggplot中绘制双y轴?

时间:2021-02-14 03:21:23

标签: r ggplot2

y1 = c(830.6225, 1051.7180, 1084.5102, 1089.1885, 1184.4557,  969.8625,  881.7043, 1047.6092,  860.3845)
y2 = c(11167.21, 11765.34, 12897.90, 13002.88, 14459.16, 14272.08, 14400.74, 13573.05, 13198.24)
x = c(0e+00, 1e-02, 1e-01, 5e-01, 1e+00, 2e+00, 5e+00, 1e+01, 1e+02)

data = data.frame(y1 = y1, y2 = y2, x = x)

ggplot(data=data,aes(x = x ,y=y1))+
  geom_line(aes(y=y1), colour="red")+
  geom_line(data = data,aes(x=x,y=y2),colour="blue")

我想要红色曲线的第一个 y 轴范围和带有范围蓝线的第二个 y 轴。你能给我提示吗?

1 个答案:

答案 0 :(得分:1)

这是你想要的吗? ggplot2 是一个固执己见的框架,其中一个观点是应该避免使用辅助轴。虽然它允许它们,但需要用户进行一些手动工作才能将所有系列都放在主轴上,然后允许辅助轴作为注释。

ggplot(data=data, aes(x = x)) +
  geom_line(aes(y = y1), colour="red") +
  geom_line(aes(y = y2 / 15), colour="blue") +
  scale_y_continuous(sec.axis = ~.*15)+
  theme(axis.text.y.left = element_text(color = "red"),
        axis.text.y.right = element_text(color = "blue"))

enter image description here