【问题标题】:How to draw dual y-axis in ggplot with different y ranges? [duplicate]如何在具有不同y范围的ggplot中绘制双y轴? [复制]
【发布时间】:2021-05-17 09:38:57
【问题描述】:
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 轴范围。能给我提示吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案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"))
    

    【讨论】:

    • 谢谢,我还有一个问题。如何为每个案例添加smooth line?我知道如果我们有一个折线图,我们可以使用stat_smooth(method = "lm", se = FALSE, color = "green", formula = y ~ x) 来添加lm 平滑线。在这种情况下,我有两条线。请给我提示?
    • geom_smooth(aes(y = y1), method = "lm", se = FALSE, color = "green", formula = y ~ x) + geom_smooth(aes(y = y2/15), method = "lm", se = FALSE, color = "purple", formula = y ~ x) +
    猜你喜欢
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多