Kostas Kot
Kostas Kot

Reputation: 11

ggplot barplot mean values on graph

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!

Upvotes: 1

Views: 7281

Answers (2)

Roman
Roman

Reputation: 17668

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

enter image description here

Upvotes: 4

giocomai
giocomai

Reputation: 3528

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)

Upvotes: 0

Related Questions