条形图上带有标签的Geom_text问题

时间:2019-04-03 07:46:04

标签: r ggplot2 geom-text

基于虹膜数据集,我试图创建一个条形图,其中每个物种的平均间隔长度作为每个条的标签。

可复制的示例:

#load data
iris1 <- as.data.frame(iris)

#packages
library(ggplot2) #visualizations

#create bar chart with average Sepal Length for each Species as the label
ggplot(data = iris1, aes(x = iris1$Species, y = iris1$Sepal.Length)) + 
  geom_bar(stat = "summary", fun.y ="mean",  fill = "light blue") +
  labs(title = "Sepal Length by Species", x = "Species", y = "Sepal Length") +
  geom_text(label = iris1$Sepal.Length)

输出: enter image description here

ggplot(data = iris1, aes(x = iris1$Species, y = iris1$Sepal.Length)) + 
  geom_bar(stat = "summary", fun.y ="mean",  fill = "light blue") +
  labs(title = "Sepal Length by Species", x = "Species", y = "Sepal Length") +
  geom_text(label = mean(iris1$Sepal.Length))

输出: enter image description here

我希望该图显示每个条形(setosa,杂色和弗吉尼亚州)的平均间隔长度的1个标签。

1 个答案:

答案 0 :(得分:2)

您可以尝试以下操作:

ggplot(iris1, aes(x = Species, y = Sepal.Length)) + 
  stat_summary(fun.y=mean, geom="bar", fill = "light blue") +
  stat_summary(aes(label=..y..), fun.y=mean, geom="text", size=8)

输出:

enter image description here