【问题标题】:Assign one column to the primary axis and the other to secondary y-axis in ggplot2在ggplot2中将一列分配给主轴,另一列分配给次要y轴
【发布时间】:2021-09-16 02:07:49
【问题描述】:

我今天早上正在讨论如何正确设置我的 ggplot 的主轴和次轴。我有一个看起来像这样的数据

df <- data.frame(Day = seq(1:10),
  Temperature = seq(4,7,length=10),
  Moisture = seq(5,9,length=10)) 

   Day Temperature Moisture
1    1    4.000000 5.000000
2    2    4.333333 5.444444
3    3    4.666667 5.888889
4    4    5.000000 6.333333
5    5    5.333333 6.777778
6    6    5.666667 7.222222
7    7    6.000000 7.666667
8    8    6.333333 8.111111
9    9    6.666667 8.555556
10  10    7.000000 9.000000

我只是想将温度分配给主要的 y 轴,将水分分配给次要的 y 轴。

到目前为止我的努力没有奏效:任何建议都非常感谢。该主题中以前的帖子对我没有帮助。

ggplot(df,aes(Day)) +
  geom_line(aes(y=Temperature), color="#45BF44") +
  geom_line(aes(y=Moisture),   color="#02BEC4") +
  scale_y_continuous(limits = c(3.5,7),
                     name = "Temp",
                     sec.axis = sec_axis(~ 1.2+ ., name="Moist")) 

我希望蓝线的 5 与辅助轴上的 5 一致,而不是主轴的 5

【问题讨论】:

    标签: r ggplot2 dplyr tidyverse


    【解决方案1】:

    这是你所期望的吗?

    library(ggplot2)
    ggplot(df,aes(Day)) +
      geom_line(aes(y=Temperature), color="#45BF44") +
      geom_line(aes(y=Moisture-1.2),   color="#02BEC4") +
      scale_y_continuous(limits = c(3.5,7),
                         name = "Temp",
                         sec.axis = sec_axis(~ 1.2+ ., name="Moist"))
    

    【讨论】:

    • 志强您好,感谢您的回答。这是破解它并绘制它的好方法。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    相关资源
    最近更新 更多