【问题标题】:r - Ploting two plots (3 variables) with one x-axes in ggplotr - 在 ggplot 中用一个 x 轴绘制两个图(3 个变量)
【发布时间】:2014-07-01 00:47:43
【问题描述】:

我试图在一张图中绘制两个流量和一个降雨数据。我把它分成上下两部分,如下图所示。在这里,我对这个情节有两个问题并且花了很长时间但无法解决。

  1. 为什么观察到的流总是黑色的,即使我把它设置为蓝色?我是否不小心使用了其他一些参数来覆盖它?
  2. 最重要的是,如何为底部图添加图例?我尝试了许多不同的代码,但它们似乎对我不起作用。

    x = data.frame(date = Date, rain = Obs_rain, obsflow = Obs_flow,simflow=Sim_flow)
    
    g.top <- ggplot(x, aes(x = date, y = rain, ymin=0, ymax=rain)) +
             geom_linerange() +
             scale_y_continuous(trans = "reverse") +
             theme_bw() +
             theme(plot.margin = unit(c(1,5,-30,6),units="points"),
             axis.title.y = element_text(vjust =0.3)) +
             labs(x = "Date",y = "Rain(mm)")
    
    g.bottom <- ggplot(x, aes(x = date, y = obsflow, ymin=0, ymax=obsflow), colour = "blue",size=0.5) +
             geom_linerange() +  #plot flow
             geom_linerange(aes(y = simflow, ymin=0, ymax=simflow), colour = "red", size =0.5)+ 
             labs(x = "Date", y = "River flow (ML/day)") +
             theme_classic() +
             theme(plot.background = element_rect(fill = "transparent"),
             plot.margin = unit(c(2,0,1,1),units="lines"))
    
    grid.arrange(g.top,g.bottom, heights = c(1/5, 4/5)) 
    

更新:

我已经解决了蓝线颜色的问题。我不小心把论据放在了错误的地方。但我仍然在与传奇作斗争。

    g.bottom <- ggplot(x, aes(x = date, y = obsflow, ymin=0, ymax=obsflow)) +
                geom_linerange(colour = "blue",size=0.5) +  #plot flow

【问题讨论】:

  • 用于底部图。融化您的数据,即您应该有 3 列: 1=date, 2=flow (obs vs sim), 3=value 。然后使用 aes(x=data,y=value,color=flow)
  • 嗨,皮埃尔,我不确定您何时说 3 列:1=日期、2=流量(obs vs sim)、3=值。您能否解释一下第二列或第三列是什么意思?

标签: r graph plot ggplot2


【解决方案1】:

作为@pierre 含义的解释...使用reshape2::melt 将您的数据从“宽”格式转换为“长”格式,以便每个日期的流类型在一列flow_type 中,并且值是另一个 (flow_val)。然后将flow_type 指定为分配颜色的分组变量:

require(reshape2)

x.melted <- melt(x, id.vars = c("date", "rain"), variable.name="flow_type",
                 value.name="flow_val")

g.bottom <- ggplot(x.melted, aes(x = date),size=0.5) +
  geom_linerange(aes(ymin=0, ymax=flow_val, colour=flow_type)) +  #plot flow
  labs(x = "Date", y = "River flow (ML/day)") +
  theme_classic() +
  theme(plot.background = element_rect(fill = "transparent"),
        plot.margin = unit(c(2,0,1,1),units="lines"), 
        legend.position="bottom") + 
  scale_colour_manual(guide = guide_legend(title = "Flow Type"), 
                      values = c("obsflow"="blue", "simflow"="red"))

【讨论】:

  • 非常感谢,非常感谢。但是我也很好奇如果我想使用不同的线型,我只是在colour=flow_type 之后添加linetype=flow_type 但是如何在一个插槽中绘制图例?现在它是一个颜色图例和一个线型图例。
  • 在这里试试这个答案:stackoverflow.com/questions/12410908/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 1970-01-01
  • 2018-08-30
  • 2016-10-27
相关资源
最近更新 更多