【问题标题】:ggplot2 - How to add additional text labelsggplot2 - 如何添加额外的文本标签
【发布时间】:2019-08-20 19:04:32
【问题描述】:

我在使用 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

【问题讨论】:

  • 也许改成长格式?您可以发布示例数据吗?请使用dput(Data) 的输出编辑问题。或者,如果 dput(head(Data, 20)) 的输出太大。
  • 编辑问题以制作完全可复制的示例。

标签: r ggplot2


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多