首页 > 解决方案 > ggplot2 - 如何添加额外的文本标签

问题描述

我遇到了一些麻烦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 手段的线图和手段 an 的文本标签。如果我们想添加另一条线/曲线,我们只需添加:

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 上的平均值并打印文本标签?看来我只能将它用于 "main" y

标签: rggplot2

解决方案


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

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

在此处输入图像描述


推荐阅读