[英]ggplot2 - How to add additional text labels
I am having some trouble with ggplot
and stat_summary
. 我在使用
ggplot
和stat_summary
时遇到了一些麻烦。
Please consider following data: 请考虑以下数据:
head(mtcars)
data<-mtcars
data$hp2<-mtcars$hp+50
Please consider following code: 请考虑以下代码:
ggplot(mtcars, aes(x = cyl, y = hp)) +
stat_summary(aes(y = hp, group = 1), fun.y=mean, colour="red", geom="line",group=1) +
stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE, vjust=-0.7, aes( label=round(..y.., digits=0)))
The code will produce line plot with means of hp and text labels for means ans well. 该代码将生成带有hp均值的均线图,以及均值均很好的文本标签。 If we would like to add another line/curve we simply have to add:
如果我们想添加另一条线/曲线,我们只需添加:
ggplot(mtcars, aes(x = cyl, y = hp)) +
stat_summary(aes(y = hp, group = 1), fun.y=mean, colour="red", geom="line",group=1) +
stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE, vjust=-0.7, aes( label=round(..y.., digits=0)))+
stat_summary(aes(y = hp2), fun.y=mean, colour="blue", geom="line",group=1)
Now comes the tricky part: 现在是棘手的部分:
How to use stat_summary
with geom="text"
but for the hp2 ie how to technically force stat_summary
to calculate means on hp2 and print the text labels? 如何将
stat_summary
与geom="text"
一起使用,但对于hp2,即如何从技术上强制stat_summary
在hp2上计算均值并打印文本标签? It seems that I can only use it for the "main" y
. 看来我只能将它用于“主要”
y
。
This type of problem, that asks for graphs of related vector columns, is almost always a wide-to-long data format reshaping problem. 这种类型的问题要求相关向量列的图形,几乎总是一个从宽到长的数据格式重塑问题。
library(ggplot2)
data_long <- reshape2::melt(data[c('cyl', 'hp', 'hp2')], id.vars = 'cyl')
head(data_long)
ggplot(data_long, aes(x = cyl, y = value, colour = variable)) +
stat_summary(fun.y = mean, geom = "line", show.legend = FALSE) +
stat_summary(fun.y = mean, geom = "text", show.legend = FALSE, vjust=-0.7, aes( label=round(..y.., digits=0))) +
scale_color_manual(values = c("red", "blue"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.