ggplot(R)中的第二个Y轴

时间:2018-06-07 15:20:30

标签: r ggplot2

我正在尝试用R中的Shiny应用程序中的ggplot制作一个情节,我需要在其中设置第二个Y轴。该图有两种类型的图形:线条和条形。我想表示左边的条形(降水深度)和右边的线条(流量)。

我目前的代码是:

output$plotRout <- renderPlot({                                     
    ggplot(totalRR(),aes(x=time)) +
      geom_bar(aes(y=mm), stat = "identity",fill = "dodgerblue",color = "black") +
      geom_bar(aes(y=NetRain), stat = "identity",fill = "Cyan",color = "black") +
      geom_line(aes(y=DirRun, colour = "Direct Runoff"), stat = "identity",color = "Red") +
      geom_line(aes(y=BF, colour = "Baseflow"), stat = "identity",color = "Darkorange", linetype = "longdash") +
      scale_y_continuous("Rainfall (mm)", sec.axis = sec_axis(~.*10, name = "Flow (m3/s)")) +
      xlab("Time (h)")
  })

The result is:

enter image description here

该图左侧是流量值,右侧应该是值,而雨量值(柱子)不会显示在图表上。

我怎样才能让这个图表左边的条形图(降雨量)和右边的第二个y轴显示线条(流量)的值?

非常感谢提前。

维克多

1 个答案:

答案 0 :(得分:0)

一种解决方案是使Flow轴成为主y轴。这涉及1)使用*10缩放数据,然后2)使用/10转换辅助轴以获取Rainfall轴的正确数字:

ggplot(totalRR(),aes(x=time)) +
    geom_bar(aes(y=10*mm), stat = "identity",fill = "dodgerblue",color = "black") +
    geom_bar(aes(y=10*NetRain), stat = "identity",fill = "Cyan",color = "black") +
    geom_line(aes(y=10*DirRun, colour = "Direct Runoff"), stat = "identity",color = "Red") +
    geom_line(aes(y=10*BF, colour = "Baseflow"), stat = "identity",color = "Darkorange", linetype = "longdash") +
    scale_y_continuous("Flow (m3/s)", sec.axis = sec_axis(~./10, name = "Rainfall (mm)")) +
    xlab("Time (h)")