【发布时间】:2020-06-18 01:59:26
【问题描述】:
几年前,有人问question 为什么 geom_bar 与 yearmon 有问题。建议的解决方案不再适用于更新版本的 ggplot。
这是 ggplot 3.3.0 的一个最小示例:
library(zoo)
library(data.table)
library(ggplot2)
# geom_col can handle yearmon when only Jannuary data are conained
dt_tmp <- data.table(time_period = as.yearmon(c(2019, 2019, 2020)),
count_cases = c(1:2, 10),
group = c("a", "b", "a"))
ggplot(dt_tmp, aes(x = time_period, y = count_cases, fill = group)) +
geom_col() +
scale_x_yearmon(breaks = sort(unique(dt_tmp$time_period)))
# however with anything esle than January geom_col has trouble
dt_tmp <- data.table(time_period = as.yearmon(c(2019, 2019, 2019 + 1/12)),
count_cases = c(1:2, 10),
group = c("a", "b", "a"))
ggplot(dt_tmp, aes(x = time_period, y = count_cases, fill = group)) +
geom_col() +
scale_x_yearmon(breaks = sort(unique(dt_tmp$time_period)))
# however geom_line and geom_point can
ggplot(dt_tmp, aes(x = time_period, y = count_cases, colour = group)) +
geom_line() +
geom_point()
一旦我们将除 1 月以外的任何其他月份包括在内,我们最终会得到:
那么发生了什么变化或我缺少什么?这是一个错误吗?
【问题讨论】:
-
试试
geom_col(orientation = "x")。见this comment -
这就是答案。谢谢。我同意“我的口味会遵循一个更简单的规则:如果一个轴是一个因素 [或 yearmon],它决定了方向。如果不是,则默认为“x”。”