将标签放到ggplot2图表中

时间:2012-07-31 14:27:18

标签: r ggplot2

我正在尝试使用geom_line ggplot2 图表添加标签,这些图表包含许多点和线。由于图形具有太多的数据点和线性线,因此它看起来非常混乱。

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

我的数据框看起来像这样

> 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")first.points,但仍然不够明确。当我做最后一点时,标签被砍掉了。

是否可以在lm行上添加标签?

1 个答案:

答案 0 :(得分: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))
相关问题