2

我正在创建一个带有模型、数据点和几条水平线的 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)

这是我的示例数据框

输入(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)
4

2 回答 2

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))

在此处输入图像描述

于 2013-05-22T16:49:45.387 回答
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 文档。如果你想玩传奇,R Cookbook 关于传奇的部分可能会有所帮助。

于 2013-05-22T16:26:53.033 回答