ggplot barplot mean values on graph

若如初见. 提交于 2021-01-28 06:11:12

问题


I want to create a barplot with 2 factors and 1 continuous variable for y. Μy code is (it is based on the build-in dataset: mtcars):

data(mtcars)
x=mtcars
library(ggplot2)
ggplot(x,aes(x=factor(carb), y=mpg, fill=factor(carb)))
+geom_bar(stat="summary",fun.y="mean")
+labs(title="Barplot of Average MPG per Carbon category per # of Cylinders", y="Mean MPG",x="Carbon Category")
+facet_grid(.~factor(cyl))
+geom_text(aes(label=mpg),vjust=3)

My goal is to have (and show) the average MPG value per carbon category, per cylinder category. Is my code correct?

The main problem is, I just want the mean value shown on each bar, not all values for this combination of factor values.

For example: subset(x,c(x$carb==3 & x$cyl==8)) returns 3 different values for MPG, and the graph shows all these three!


回答1:


You can try

library(tidyverse)
mtcars %>% 
group_by(carb, cyl) %>% 
summarise(AverageMpg = mean(mpg)) %>% 
  ggplot(aes(factor(carb), AverageMpg, label=AverageMpg, fill=factor(carb))) +
  geom_col() +
  geom_text(nudge_y = 0.5) + 
  facet_grid(~cyl, scales = "free_x", space = "free_x")




回答2:


If I understand correctly, I suppose this is what you're trying to achieve.

data(mtcars)
library(tidyverse)

mtcars %>% 
  group_by(carb, cyl) %>% 
  summarise(AverageMpg = mean(mpg)) %>% 
  ungroup() %>% 
  mutate(carb = factor(carb)) %>% 

ggplot(mapping = aes(x=carb, y=AverageMpg, fill=carb)) +
  geom_col() +
  scale_y_continuous(name = "Mean MPG") +
  scale_x_discrete("Carbon Category") +
  labs(title="Barplot of Average MPG per Carbon category per # of Cylinders") +
  facet_grid(.~cyl)



来源:https://stackoverflow.com/questions/50696827/ggplot-barplot-mean-values-on-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!