2

我正在尝试向ggplot2图形添加标签,这些图形使用geom_line. 由于该图有太多的数据点和线性线,它看起来非常混乱。

我想将标签添加到线性行,以便最终用户明确知道哪些行属于哪个服务器等。

我的数据框看起来像这样

> z
Hostname    Memory  Date
ServerA         50  2012-01-01 01:00:00
ServerB         30  2012-01-01 01:00:00
ServerC         30  2012-01-01 01:00:00
ServerD         20  2012-01-01 01:00:00
ServerE         80  2012-01-01 01:00:00

ServerA         20  2012-01-02 01:00:00
ServerB         10  2012-01-02 01:00:00
ServerC         5   2012-01-02 01:00:00
ServerD         39  2012-01-02 01:00:00
ServerE         50  2012-01-02 01:00:00



p <- ggplot(z, aes(x=Date, y=Memory, colour=Hostname, size=0.1)) + 
        geom_point(size=0.1) + theme_bw

() + geom_smooth(method = "lm", se=FALSE, size = 1) + 
         theme_bw() + geom_point(size=0.2)

我尝试使用direct.label(p, "last.points")or first.points,但仍然不够清楚。当我做 last.points 时,标签被剪掉了。

是否可以在线路上放置标签lm

4

1 回答 1

0

我会更改您原始脚本中的一些设置:我添加了 group=Hostname,并从第一行删除了 size=0.1,在下一行您可以自定义 geom_point(我将其形状更改为 x),然后对于 geom_smooth 函数,您应该使用:aes(group = Hostname),最后 direct.label() 工作正常。

library(ggplot2)  
library(directlabels)  
myplot<-ggplot(z, aes(x=Date, y=Memory, group=Hostname, colour=Hostname))+  
geom_point(size=3, shape=4) +  
geom_smooth(method = "lm", aes(group = Hostname), se=FALSE, size=1)  
myplot<- direct.label(myplot, "last.points")  

据我所知,没有预先写好的方法,你应该写自己的“定位方法”,你可以试试这样的东西,其中“斜率”是lm曲线的斜率。(如您所见,它还不是动态的)

slope<-c(-30,-20, 60, 50, -40)  
label.above <- list("first.points", rot = slope, hjust = -0.5, vjust = -0.5)  
direct.label(myplot, label.above)

其中 z 是:

z<-structure(list(Hostname = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("ServerA", "ServerB", "ServerC", "ServerD", "ServerE"), class = "factor"), Memory = c(50L, 30L, 30L, 20L, 80L, 20L, 10L, 5L, 39L, 50L), Date = structure(c(2L, 2L, 2L, 2L, 2L, 3L, 3L, 1L, 3L, 3L), .Label = c("  2012-01-02 01:00:00", " 2012-01-01 01:00:00", " 2012-01-02 01:00:00"), class = "factor")), .Names = c("Hostname", "Memory", "Date"), class = "data.frame", row.names = c(NA, -10L))
于 2012-07-31T19:38:58.807 回答