[英]r - Ploting two plots (3 variables) with one x-axes in ggplot
I am trying to plot two flows and one rainfall data in one graph. 我正在尝试在一张图中绘制两个流量和一个降雨数据。 I have broke it up into top and bottom parts as shown in the following pic. 我将其分解为顶部和底部,如下图所示。 Here I have two issues with this plots and spent ages but cannot solve it. 在这里,我有两个关于该图和使用年龄的问题,但无法解决。
The most importantly is, how do I able to add a legend for the bottom plot? 最重要的是,如何为底部绘图添加图例? I tried many different codes but they don't seem to work for me. 我尝试了许多不同的代码,但它们似乎对我不起作用。
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))
Update: 更新:
I have resolved the issue with blue line colour. 我已经用蓝线解决了这个问题。 I accidently put arguments in the wrong place. 我不小心把论点放在错误的地方。 But I'm still struggling with the legend. 但是我仍然在为传奇而挣扎。
g.bottom <- ggplot(x, aes(x = date, y = obsflow, ymin=0, ymax=obsflow)) +
geom_linerange(colour = "blue",size=0.5) + #plot flow
As an explanation of what @pierre means... turn your data from "wide" to "long" format using reshape2::melt
, so that the flow type for each date is in one column flow_type
, and the value is another ( flow_val
). 作为对@pierre含义的解释...使用reshape2::melt
将数据从“宽”格式转换为“长”格式,以便每个日期的流类型在一列flow_type
,而值在另一列中( flow_val
)。 Then you specify flow_type
as the grouping variable with which to assign colour: 然后,将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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.