Home > other >  Side By Side Bar Graph Error: can only have an x or y aesthetic
Side By Side Bar Graph Error: can only have an x or y aesthetic

Time:05-07

I've been trying to create something like this graph found on Google(not stacked, but side-by-side):

enter image description here

My code starts like:

ggplot(data = bike_data_v4)  
  geom_bar(mapping = aes(ride_month, ride_duration, fill=member_casual)) 
  geom_bar(stat = "identity") 
  geom_col(position = 'dodge')

and I receive the error message:

Error in f(): ! stat_count() can only have an x or y aesthetic.

I've also tried:

ggplot(data = bike_data_v4)  
  geom_bar(mapping = aes(ride_month, ride_duration, fill=member_casual)) 
  geom_bar(stat = "identity", position = 'dodge')

No luck though :/

CodePudding user response:

If you want to have a grouped bar chart then add group aesthetics like this:

  ggplot(data = mtcars, aes(ride_month, ride_duration, fill=member_casual, group = member_casual)) 
    geom_col(position = position_dodge()) 

Here is an example with mtcars dataset:

  ggplot(data = mtcars, aes(cyl, mpg, fill=am, group = am)) 
    geom_col(position = position_dodge())

enter image description here

CodePudding user response:

Does this do what you want?

library(ggplot2)
data = mtcars

ggplot(data, aes(x = factor(carb), y = mpg, fill = factor(vs)))  
  geom_col(position = "dodge")
  • Related