'Create bar graph-find the average mpg by the number of gears
mtcars %>%
group_by(gear, mpg) %>%
summarise(m = mean(mpg)) %>%
ggplot(aes(x = mpg, y = gear)) +
geom_bar(stat = "count")
I cannot figure out to create a bargraph with the average mpg by the number of gears
Solution 1:[1]
Is that what you need?
packages
library(dplyr)
library(ggplot2)
Average mpg (m) by the number of gears
mtcars %>%
group_by(gear) %>%
summarise(m = mean(mpg)) %>%
ungroup() %>%
ggplot(aes(y = m, x = gear)) +
geom_bar(stat = "identity")
- First, we get the mean of mpg by gear. To do that, you want to group by gear (just gear. You don't need to group by mpg as well).
- Ungroup, so you have a unified dataset.
- Now you want to plot the mean you created (m) by gear. You can which of them go where. In this case, I put
gearon the x-axis and the mean of mpg on the y-axis. - Given you have specific values for the mean, you don't have to count all the values. Just plot the specific value you have there. Thus, use
stat = "identity"instead ofstat = "count"
Now you can play with colors using fill argument in aes and change the titles and axis labels.
output
Solution 2:[2]
In base R (i.e. without additional libraries) you might do
with(mtcars, tapply(mpg, gear, mean)) |>
barplot(xlab='gear', ylab='n', col=4, main='My plot')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | jay.sf |


