如何在添加的geom_lines 末尾显示标签?

How to display labels at the end of added geom_lines?

我有一个包含多列的数据框。

这是我的数据框的摘录:

    emp_dayNumber emp_dayName emp_workedDays emp_fullPrice emp_halfFare emp_monthly emp_yearly
1               1         mon           TRUE          23.7       117.20      117.66    1058.84
2               2         tue           TRUE          47.4       129.05      117.66    1058.84
3               3         wed           TRUE          71.1       140.90      117.66    1058.84

我使用 ggplot2 绘制变量 emp_fullPriceemp_halfFareemp_monthlyemp_yearly。 为了显示标签,我在网上搜索并找到了图书馆ggrepel的推荐。 它似乎有效,但仅适用于我情节中的第一个 geom_line。

我想 post 一张图片,但我无法添加图片,因为我的声誉很低。所以这里有一张糟糕的图画。

|
|
|                                  / 1209
|      ___________________________/  
|     /                          ____
|    /                 _________/
|   /__________       /
|  /           \_____/_______
| /                 /        \_______ 
|/_________________/_________________ 

如您所见,我设法获得了第一个值(emp_fullPrice,所以是 1209)的标签,但没有获得其他值的标签。

这是我的情节代码:

p<- ggplot(emp.data, aes(emp_dayNumber, emp_fullPrice))+
  geom_line(colour=1, size=1.3)+
  geom_line(aes(y=emp_halfFare),colour=2, size=1.3)+
  geom_line(aes(y=emp_monthly),colour=3, size=1.3)+
  geom_line(aes(y=emp_yearly),colour=4, size=1.3)+

  #Label at the end of the line
  geom_text_repel(
    data = subset(emp.data, emp_dayNumber == 154),
    aes(label = emp_fullPrice),
    size = 4,
    nudge_x = 5);

print(p)

据我了解,它适用于 ggplot() 中显示的值,但不适用于我用 geom_lines() 添加的值。

有人有解决办法吗? 谢谢你。

要使这对您自己来说更容易,第一步是更改数据的形状。

尝试由 ggplot 的制作者 Hadley Wickham 制作的 "reshape2" 包。

如果您在 data.frame 上应用 "melt" 函数,您最终会得到一个包含两列的 data.frame:一列用于值(您 data.frame) 和一个用于关闭值的类型(data.frame 的列名)。

举个例子:

emp.data <- data.frame("emp_dayNumber" = 1:100,
                       "emp_monthly" = rnorm(100),
                       "emp_yearly" = rnorm(100),
                       "emp_WorkedDays" = sample(c(TRUE,FALSE), 100, replace = TRUE))
library(reshape2)

## Select the colums you want to plot:
select.data <- emp.data[ , 1:3]

## Change the data.frame to a long format, and state that you want to keep "emp_dayNumber" variable
## as a separate column (as you use it for the x-axis)
plot.data <- melt(emp.data, id.vars = "emp_dayNumber")

您的数据现在应该如下所示:

  emp_dayNumber    variable      value
1             1 emp_monthly  0.4231487
2             2 emp_monthly -1.0966351
3             3 emp_monthly  0.2761555
4             4 emp_monthly  0.8575178
5             5 emp_monthly -0.8528019
6             6 emp_monthly  0.4341048

现在绘制你的数据,其中 "emp_dayNumber" 应该是你的 x,"value" 你的 y 和 "variable" 你的颜色

ggplot(toplot.data, aes(x = "emp_dayNumber", y = "value", color = "variable")) +
    geom_line()

尝试始终将此应用于所有绘图功能。这最终会为您节省很多时间。 有关长格式和宽格式的更多说明,请参阅:http://www.cookbook-r.com/Manipulating_data/Converting_data_between_wide_and_long_format/

使用这个,您现在可以应用 "mnm" 评论中链接的 post 中所述的解决方案,或者使用 "ggrepel",因为您现在只使用一个 y 变量!