我有一个简单的数据帧(WF),如下所示:
head(wf)
Date Gals Days GpD GpM
2016-10-21 6.0 1 6.0 186.0
2016-10-22 6.0 1 6.0 186.0
2016-10-23 12.4 1 12.4 384.4
2016-10-24 26.8 1 26.8 830.8
2016-10-25 33.3 1 33.3 1032.3
2016-10-26 28.3 1 28.3 877.3
我要做的是时间序列图Date vs. Gals,并为平均值和中位数设置一条水平线。我面临的故障正是在情节上正确地传达了一个传奇。我的代码到目前为止:
require(ggplot2)
p1<-ggplot(data=wf, aes(Date, Gals, lty = 'Gals'), colour="black") +
geom_line(colour="black") +
scale_x_date(date_labels="%b-%Y", date_breaks="2 month") +
xlab("") + ylab("Gallons per Day") + scale_linetype('Water Usage') +
geom_hline(aes(yintercept=as.numeric(mean(wf$Gals)), linetype = "Mean"),
color = "red", size=1) +
geom_hline(aes(yintercept=as.numeric(median(wf$Gals)),linetype="Median"),
color = "orange", size=1)
print(p1)
图例线颜色错误。这样做的正确方法是什么?
V ------------------------ V编辑原始问题添加...
我希望这有效,我将使用Axeman的解决方案来获得:
l1<-paste("Mean:", round(mean(wf$Gals), 2))
l2<-paste("Median:", round(median(wf$Gals), 2))
ggplot(wf, aes(Date, Gals)) +
scale_x_date(date_labels="%b-%Y", date_breaks="4 month") +
geom_line(aes(lty = "Gals", color = "Gals", group=1)) +
geom_hline(aes(yintercept = mean(wf$Gals), linetype = "Mean", color =
"Mean"), size=1) +
geom_hline(aes(yintercept = median(wf$Gals), linetype = "Median", color =
"Median"), size = 1) +
scale_linetype('Water Usage') +
scale_color_manual('Water Usage-New', labels = c("Gals", l1, l2),
values=c('Gals' = 'black', 'Mean' = 'red', 'Median' =
'orange')) +
xlab("") + ylab("Gallons per Day")
产生以下内容:
“水的使用 - 新”是我需要的,但是如何摆脱第一个传奇或修改它而不添加scale_color_manual(...)
的新传奇?
如果你设置美学,就像使用color = "red"
一样,它将不会在图例中显示。只有你在aes
中将它们映射到包括它们。您可以使用与线型相同的颜色映射颜色,然后正确配置比例:
ggplot(wf, aes(Date, Gals)) +
geom_line(aes(lty = "Gals", color = "Gals", group = 1)) +
geom_hline(aes(yintercept = mean(wf$Gals), linetype = "Mean", color = "Mean"), size=1) +
geom_hline(aes(yintercept = median(wf$Gals), linetype = "Median", color = "Median"), size = 1) +
scale_linetype('Water Usage') +
scale_color_manual(
'Water Usage',
values = c('Gals' = 'black', 'Mean' = 'red', 'Median' = 'orange')
) +
xlab("") + ylab("Gallons per Day")
wf <- data.table::fread('Date Gals Days GpD GpM
2016-10-21 6.0 1 6.0 186.0
2016-10-22 6.0 1 6.0 186.0
2016-10-23 12.4 1 12.4 384.4
2016-10-24 26.8 1 26.8 830.8
2016-10-25 33.3 1 33.3 1032.3
2016-10-26 28.3 1 28.3 877.3')