当我在R中绘制两个” y”轴时,是否存在ggplot2形式仅”反转”一个轴(geom_bar())

Is there a ggplot2 form to “reverse” only one axis (geom_bar() ) when i plot two “y” axis in R

我正在尝试绘制两个" y"轴,第一个具有%的"土壤水分含量"的轴(geom_line())和一个带有降水量数据的geom_bar()。问题是降水图。我需要"反转"情节。

我现在有这张图表:

Soil

我需要土壤水分时间序列如上图所示,但降水量如以下图所示

precipitation

" pp_melt"数据框是一个包含3列的数据框:fecha =日期(每天),value =每天的降水量cm,变量=如果水来自降水或灌溉,则为

1
2
3
4
5
6
7
8
9
gpp = ggplot() +
  geom_line(data = hum_melt10,aes(x = fecha, y = value, color = variable), size = 1.0) +
  xlab("Fecha") +
  geom_bar(data = pp_melt, aes(x = fecha, y = value / 20, fill  = variable), stat="identity",position = 'dodge', na.rm = TRUE) +
  scale_y_continuous(name ="Contenido de agua (%)",sec.axis = sec_axis(~.*20, name ="pp y riego (cm)")) +
  scale_x_date(breaks = '2 month', labels = fecha, date_labels = '%b %y') +
  theme(plot.title = element_text(lineheight=.8, face="bold", size = 20)) +
  theme_bw() + theme( panel.grid.major = element_blank(),
                      panel.grid.minor = element_blank(), axis.line = element_line(colour ="black"), aspect.ratio = 0.3)

谢谢!


同意@dmp,使用sec_axis仅将标签添加到右侧;如果要翻转绘图中的外观,则需要

  • 使用scale_y_reverse(),这将翻转所有内容;
  • 手动翻转美学系列;或者
  • 手动翻转序列本身的数据。
  • 由于您只想反转一个数据系列,而不是全部,所以#1出局了。 #3确实可以工作,尽管您仍然需要修改对sec_axis的调用,所以我只做#2就可以简化它。

    1
    2
    3
    4
    5
    6
    library(ggplot2)
    mt <- transform(mtcars, rn = 1:nrow(mtcars))
    ggplot(mt) +
      geom_bar(aes(x = rn, y = drat), stat ="identity") +
      geom_line(aes(x = rn, y = disp/100), stat ="identity", color ="red", size = 1) +
      scale_y_continuous(sec.axis = sec_axis(~ . * 100))

    ggplot

    1
    2
    3
    4
    5
    ggplot(mt) +
      geom_bar(aes(x = rn, y = drat), stat ="identity") +
      geom_line(aes(x = rn, y = 5 - disp/100), stat ="identity", color ="red", size = 1) +
      # changes:                ^^^             vvv
      scale_y_continuous(sec.axis = sec_axis(~ (5 - .) * 100))

    ggplot

    (重要的是要记住,翻转点(上例中的5)基于主轴刻度,而不是新数据。)

    未经测试,我怀疑您代码的修复将是这样(其中从图中推断出9)。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    gpp = ggplot() +
      geom_line(data = hum_melt10,aes(x = fecha, y = value, color = variable), size = 1.0) +
      xlab("Fecha") +
      geom_bar(data = pp_melt, aes(x = fecha, y = 9 - value / 20, fill  = variable), stat="identity",position = 'dodge', na.rm = TRUE) +
      #  changes:                                 ^^^                          vvv
      scale_y_continuous(name ="Contenido de agua (%)", sec.axis = sec_axis(~(9 - .)*20, name ="pp y riego (cm)")) +
      scale_x_date(breaks = '2 month', labels = fecha, date_labels = '%b %y') +
      theme(plot.title = element_text(lineheight=.8, face="bold", size = 20)) +
      theme_bw() + theme( panel.grid.major = element_blank(),
                         panel.grid.minor = element_blank(), axis.line = element_line(colour ="black"), aspect.ratio = 0.3)