【问题标题】:Why can't geom_col no longer handle yearmon [duplicate]为什么 geom_col 不能再处理 yearmon [重复]
【发布时间】: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”。”

标签: r ggplot2


【解决方案1】:

Henrik 在他的评论中给出了答案:geom_col(orientation = "x")

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多