如何按日期 x 轴顺序显示箱线图?

How to diplay the boxplot in order with date x - axis?

我怎样才能按月顺序排列,x 轴不是日期 class 它的字符?我尝试使用重新排序和排序它对我的情况不起作用。

两种方法。

虚假数据:

set.seed(42) # R-4.0.2
dat <- data.frame(
  when = sample(c("Apr20", "Feb20", "Mar20"), size = 500, replace = TRUE),
  charge = 10000 * rexp(500)
)
ggplot(dat, aes(charge, when)) +
  geom_boxplot() +
  coord_flip()


Date class

这就是我所说的“正确方法 (tm)”,原因有二:如果数据是 date-like,我们就使用 Date;并允许 R 自然地.

处理排序
dat$when2 <- as.Date(paste0("01", dat$when), "%d%b%y")
ggplot(dat, aes(charge, when2, group = when)) +
  geom_boxplot() +
  coord_flip() +
  scale_y_date(labels = function(z) format(z, format = "%b%y"))

(我应该注意,我需要 when2group=when:因为 when2 是一个连续变量,ggplot2 不会变成 auto-group基于它的东西,所以我们需要 group=.)


factor

我认为这是错误的方法,原因有二:(1) 不使用日期作为它们本来的数字数据; (2) 您拥有的月份越多,您就越需要手动控制因素内的水平。

不过,话虽如此:

dat$when3 <- factor(dat$when, levels = c("Feb20", "Mar20", "Apr20"))
ggplot(dat, aes(charge, when3)) +
  geom_boxplot() +
  coord_flip()

(您可以轻松地覆盖 dat$when 而不是创建新变量 dat$when3,但我将其分开,因为我在 code-testing 期间来回切换。坦率地说,如果您更喜欢 而不是 Date 路线,然后这样做也可以正确地订购其他东西。)