Home > Software design >  Create bar graph-find the average mpg by the number of gears
Create bar graph-find the average mpg by the number of gears

Time:02-22

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")
  1. 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).
  2. Ungroup, so you have a unified dataset.
  3. 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.
  4. 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 of stat = count

Now you can play with colors using fill argument in aes and change the titles and axis labels.

output

enter image description here

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

enter image description here

  •  Tags:  
  • r
  • Related