如何在 ggplot2 中显示多个箱形图的 x 轴标签的分类组

How to Display Categorical Groups for x-axis Label of Multiple Box plots in ggplot2

我正在尝试检查一年中每个月每天从 NYC 出发的航班分布。我使用的数据集是“nycflights13”,它可以作为一个包安装。然后,我按如下方式转换数据:

# load
flights <- nycflights13::flights

# rid NA
flights <- flights %>% tidyr::drop_na(tailnum)

# filter out only flights going FROM NYC and add month
flights_with_month <- flights %>%
  filter(origin != "EWR") %>%
  mutate(mth = month(time_hour), label = TRUE)

# calculate flights per day
flights_with_month <- flights_with_month %>%
  group_by(mth, day) %>%
  mutate(total_daily_flights = n())

# making boxplots
ggplot(flights_with_month, aes(y = total_daily_flights, group = mth)) +
  geom_boxplot()

这是我得到的箱线图;您会注意到 x 轴不是月份的名称,而且它们似乎也没有从一月到十二月排序。

您的代码有两个问题。 mutate(mth = month(time_hour), label = TRUE) 应该是 mutate(mth = month(time_hour, label = TRUE)),你的 ggplot 应该设置 x = mth 而不是 grp = mth。数据以正确的顺序绘制,但标签不正确。

# load
flights <- nycflights13::flights

# rid NA
flights <- flights %>% tidyr::drop_na(tailnum)

# filter out only flights going FROM NYC and add month
flights_with_month <- flights %>%
  filter(origin != "EWR") %>%
  mutate(mth = month(time_hour, label = TRUE))

# calculate flights per day
flights_with_month <- flights_with_month %>%
  group_by(mth, day) %>%
  mutate(total_daily_flights = n())

# making boxplots
ggplot(flights_with_month, aes(y = total_daily_flights, x = mth)) +
  geom_boxplot()