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
CodePudding user response:
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
gear
on 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
CodePudding user response:
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')