我对在 R 中绘制图表相当陌生。我正在尝试创建两个类似于下图的图例。下图是前一年的数据,我正在更新它,但需要重写代码。到目前为止,我的数据看起来与底部数据相同(具有更新的数据),只是水平线没有显示在图例中。但是,我需要制作两个图例,如下所示,但只设置了年份部分,并且我很困惑如何更改线条的名称、线条类型和颜色,同时将它们从年份组中分离到单独的图例中。
我的数据示例:
# Groups: Year [6]
Year Month Temp
<fct> <ord> <dbl>
1 2014 Mar 14.9
2 2014 Apr 16.6
3 2014 May 20.5
4 2014 Jun 22.0
5 2014 Jul 23.9
6 2014 Aug 24.3
7 2014 Sep 24.4
8 2014 Oct 22.1
9 2014 Dec 13.6
10 2015 Jan 11.5
# ... with 46 more rows
到目前为止我的代码:
ggplot(wq4, aes(x=Month,y=Temp, color = Year)) +
geom_line(aes(color = Year, group = Year)) +
labs(y = "Average Temperature (C)") +
geom_hline(aes(yintercept = 5), color = "red", linetype="dashed") +
geom_hline(aes(yintercept = 15), color = "dark green", linetype="dashed")
最佳答案
您可以尝试使用 ggnewscale,首先使用与您的数据格式相同的内容:
MTH = months(seq(as.Date("1910/1/1"), as.Date("1910/12/1"), "months"))
wq4 = data.frame(Year=factor(rep(2014:2018,each=12)),
Month=factor(rep(MTH,5),levels=MTH,ordered=TRUE),
Temp=sample(10:25,60,replace=TRUE))
在绘图之前,为截距创建一个数据框:
library(ggnewscale)
library(ggplot2)
intercept_DF = data.frame(y=c(5,15),label=c("Temp1","Temp2"))
ggplot(wq4) +
geom_line(aes(x=Month,y=Temp, color = Year,group=Year)) +
labs(y = "Average Temperature (C)") +
new_scale_color()+
geom_hline(data=intercept_DF,aes(yintercept = y,col=label),linetype="dashed")+
scale_color_manual(name="Threhold",values=c("red","darkgreen"))
仍在弄清楚如何对两个图例进行排序(如果可能的话)
关于r - 如何使用 ggplot 2 制作两个图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60309874/