Solution For Side By Side Bar Graph Error: can only have an x or y aesthetic

Solution For Side By Side Bar Graph Error: can only have an x or y aesthetic

我在制作并排条形图时遇到了问题,其中一列包含字符 (ride_month),一列包含骑手两种类型的总数字数据 (ride_duration)( member_casual).

ggplot(data=bike_data_v4)+
+   geom_bar(mapping = aes(x=ride_month,fill=member_casual))+
+   geom_col(position = "dodge")

Error in `check_required_aesthetics()`:
! geom_col requires the following missing aesthetics: x and y
Run `rlang::last_error()` to see where the error occurred.

我的数据集最初是这样的:

为了解决我的问题,我创建了一个新的数据集分组 member_casual 和 ride_month。接下来,我通过管道传输了 ride_duration.

的总和
bike_data_removedcols_V2 <- bike_data_removedcols %>% 
  group_by(member_casual, ride_month) %>%
  summarise(ride_duration_sum=sum(ride_duration))

我将新创建的数据集应用于这个 ggplot 函数:

ggplot(data = bike_data_removedcols_V2, aes(ride_month, ride_duration_sum, fill=member_casual, group = member_casual))+
      geom_col(position = position_dodge())

成功!

如果您想要一个分组条形图,请添加 group 美学,如下所示:

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

这里是 mtcars 数据集的示例:

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

这是你想要的吗?

library(ggplot2)
data = mtcars

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