如何在r中的ggplot中添加图例

fdx2calv  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(158)

如何使用ggplot2将图例添加到此图中?

我使用下表来绘制此图,这是该表:

我使用了以下代码来绘制这个图:

## plot the results 
ggplot(MeRe2, aes(x= Years, y=BAU))+
  geom_point(aes(x=Years, y=BAU), colour=("red"))+
  geom_point(aes(x=Years, y=Lw), colour=("orange"))+
  geom_point(aes(x=Years, y=Md), colour=("blue"))+
  geom_point(aes(x=Years, y=High), colour=("green"))+
  geom_line(aes(x=Years, y=BAU), colour="red")+
  geom_line(aes(x=Years, y=Lw), colour="orange")+
  geom_line(aes(x=Years, y=Md), colour="blue")+
  geom_line(aes(x=Years, y=High), colour="green")+
  scale_x_continuous(breaks = MeRe2$Years)+
  xlab("Years from Now")+ylab(" Total SOC Stocks in BC Soils (TonC/ha)")

我需要在这个图的右上角做一个图例来显示每一行的含义,比如:
SSM
BAU =红线
低=橙子线
中=蓝线
高=绿色线

zi8p0yeb

zi8p0yeb1#

我们可以使用labs()函数添加图例标题,使用scale_color_manual()函数指定每行的颜色和标签。

library(ggplot2)

ggplot(MeRe2, aes(x = Years)) +
  geom_point(aes(y = BAU, color = "BAU")) +
  geom_point(aes(y = LW, color = "Low")) +
  geom_point(aes(y = Md, color = "Medium")) +
  geom_point(aes(y = High, color = "High")) +
  geom_line(aes(y = BAU, color = "BAU")) +
  geom_line(aes(y = LW, color = "Low")) +
  geom_line(aes(y = Md, color = "Medium")) +
  geom_line(aes(y = High, color = "High")) +
  scale_color_manual(name = "SSM",
                     values = c("BAU" = "red", "Low" = "orange", "Medium" = "blue", "High" = "green"),
                     labels = c("BAU", "Low", "Medium", "High")) +
  scale_x_continuous(breaks = MeRe2$Years) +
  xlab("Years from Now") +
  ylab(" Total SOC Stocks in BC Soils (TonC/ha)")

相关问题