r - ggplot2 - 如何添加额外的文本标签
问题描述
我遇到了一些麻烦ggplot
和stat_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_summary
但geom="text"
对于 hp2 即如何在技术上强制stat_summary
计算 hp2 上的平均值并打印文本标签?看来我只能将它用于 "main" 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"))
推荐阅读
- java - 为什么 servlet API 不提供过滤器的排除模式?
- angular - Angular7 和 NgbModal:如何删除默认的自动对焦
- javascript - 在单词数组中找到反转的单词
- rabbitmq - Spring RabbitMQ 事务和队列溢出
- python - 具有不同大小的输出和状态的 RNNCell
- image - .pdf 总是矢量图像吗?
- powerbi - powerbi 中带有 2 个图表的一致图例颜色
- laravel - laravel 护照 oauth2 实时服务器未经身份验证 401
- java - 使用条件 API 确定实体字段类型,而不会在 intelij / 编译器中显示警告
- javascript - D3.js - 在饼图中填充颜色的问题