1

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!

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

That is exactly what I was looking for. Thanks!
Feel free to accept the answer, if you're happy with it.
0

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)

1 Comment

Thank you for the answer ! I suppose that +geom_bar(stat="summary",fun.y="mean") takes care of the mean calculation (If I am not mistaken). The problem is how can I show the mean values only, within my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.