我有一个包含几列的数据框。
这是我数据框中的摘录:
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_fullPrice
,emp_halfFare
,emp_monthly
和emp_yearly
。
为了显示标签,我在网上搜索并找到了有关库 ggrepel 的建议。
它似乎有效,但仅适用于我绘图中的第一个geom_line。
我想发布图片,但由于信誉不佳,无法添加图片。因此,这是一张肮脏的图画。
|
|
| / 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()
添加的值。
有人可以解决吗? 谢谢。
答案 0 :(得分:0)
让您自己更轻松地完成此任务的第一步是更改数据的形状。
尝试ggplot的制造商Hadley Wickham制作的“ reshape2”软件包。
如果要在data.frame上应用“融化”功能,则最终将得到一个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”或“ ggrepel”链接的帖子中所述的解决方案,因为您现在仅使用一个y变量!