繁体   English   中英

ggplot2-如何添加其他文本标签

[英]ggplot2 - How to add additional text labels

我在使用ggplotstat_summary时遇到了一些麻烦。

请考虑以下数据:

head(mtcars)
data<-mtcars
data$hp2<-mtcars$hp+50

请考虑以下代码:

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)))

该代码将生成带有hp均值的均线图,以及均值均很好的文本标签。 如果我们想添加另一条线/曲线,我们只需添加:

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) 

现在是棘手的部分:

如何将stat_summarygeom="text"一起使用,但对于hp2,即如何从技术上强制stat_summary在hp2上计算均值并打印文本标签? 看来我只能将它用于“主要” y

这种类型的问题要求相关向量列的图形,几乎总是一个从宽到长的数据格式重塑问题。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM