我正在创建一个带有模型,数据点和几条水平线的ggplot2图。我需要能够在图表的底部放置一个图例,表示蓝色线是模型,红色是最大值,橙色是阈值等。
到目前为止,我有这个:
ggplot(df, aes(DATE, RELATIVE_PERCENT)) +
geom_point(colour="black", size=0.8) +
geom_smooth(method="loess", size=1, colour="blue", se=T) +
scale_x_datetime(breaks = "1 hours") +
theme_bw() +
geom_hline(aes(yintercept = 100), col="red", size=1.5) +
ylab("Relative CPU Utilization") +
xlab("Date") +
ggtitle("DB CPU Utilization") +
geom_hline(aes(yintercept = 70), col="orange", size=1.5)
这是我的样本数据框
dput(DF)
structure(list(DATE = structure(c(1365717060, 1365717090, 1365717120,
1365717150, 1365717180, 1365717210, 1365717240, 1365717270, 1365717300,
1365717330, 1365717360, 1365717390, 1365717420, 1365717450, 1365717480,
1365717510, 1365717540, 1365717570, 1365717600, 1365717630), class = c("POSIXct",
"POSIXt"), tzone = ""), RELATIVE_PERCENT = c(26, 26, 26, 26,
26, 26, 25, 26, 26, 27, 25, 26, 26, 26, 26, 26, 26, 27, 27, 27
)), .Names = c("DATE", "RELATIVE_PERCENT"), class = "data.frame", row.names = 5740:5759)
答案 0 :(得分:2)
我可能接近这样的传奇:
df <- data.frame(x = 1:10,
y = runif(10))
max_min <- data.frame(y = c(0,1),
grp = c('min','max'))
ggplot(df)+geom_smooth(aes(x = x,y = y,colour = "model")) +
geom_hline(data = max_min,aes(yintercept = y,colour = grp))
答案 1 :(得分:0)
我不会把它称为优雅,但这是一个有效的解决方案:
# generate general plot
p <- ggplot(df, aes(DATE, RELATIVE_PERCENT)) +
# add the points and the smoothing
geom_point(aes(colour = "data"), size=0.8) +
geom_smooth(aes(colour = "smoothing"), method="loess", size=1, se=T, show_guide=TRUE) +
# add the lines
geom_hline(aes(yintercept = 100, colour ='overkill'), show_guide = TRUE, size=1.5) +
geom_hline(aes(yintercept = 70, colour ='warning'), show_guide = TRUE, size=1.5) +
# adjust the colours to those you wanted
scale_colour_manual(values = c("black","red", "blue", "orange"))
# stick the legend on the bottom
+ theme( legend.position = "bottom")
现在,有关其中任何一项的详细信息,请查看ggplot2 documentation。如果你想玩传说,R Cookbook section on legends可能会有所帮助。