![](/img/trans.png)
[英]Two graphs with the same arguments have different x-axes in ggplot
[英]r - Ploting two plots (3 variables) with one x-axes in ggplot
我正在嘗試在一張圖中繪制兩個流量和一個降雨數據。 我將其分解為頂部和底部,如下圖所示。 在這里,我有兩個關於該圖和使用年齡的問題,但無法解決。
最重要的是,如何為底部繪圖添加圖例? 我嘗試了許多不同的代碼,但它們似乎對我不起作用。
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
作為對@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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.