【问题标题】:Remove date columns with no data in ggplot2 geom_bar [duplicate]删除ggplot2 geom_bar中没有数据的日期列[重复]
【发布时间】:2017-09-04 13:05:23
【问题描述】:

我想隐藏 ggplot2 中没有数据的列。这是使用 nycflights13 库的可重现示例:

library(nycflights13)
library(dplyr)
library(ggplot2)

small_data <- flights %>%
  mutate(date = lubridate::make_date(year, month, day)) %>%
  filter(year == 2013, 
         month ==3)

ggplot(small_data) +
  geom_bar(aes(date)) +
  scale_x_date(date_labels = "%d - %b", date_breaks = "1 day") +
  theme(axis.text.x = element_text(angle = 65, hjust = 1))

正如你所看到的,虽然我只选择了 3 月的数据,但我有 2 月 28 日和 4 月 1 日的列标题。

我尝试了以下方法:

hide missing dates from x-axis ggplot2(该解决方案不再有效)

设置(date_)breaks = levels(factor(small_data$date))

请帮我隐藏不必要的栏。

【问题讨论】:

  • 选项 expand=c(0,0) 调整 x 比例,使其不显示不必要的日期。添加 "scale_x_date(date_labels = "%d - %b", date_breaks = "1 day", expand=c(0,0))"

标签: r ggplot2


【解决方案1】:

或者我们可以设置scale_x_date(..., expand = c(0,0)):

ggplot(small_data) +
    geom_bar(aes(date)) +
    scale_x_date(date_labels = "%d - %b", date_breaks = "1 day",
                 expand = c(0,0)) +
    theme(axis.text.x = element_text(angle = 65, hjust = 1))

【讨论】:

    【解决方案2】:

    我们可以在 breaks 参数中指定日期分隔符(而不是在 date_breaks 中)。

    ggplot(small_data) +
      geom_bar(aes(date)) +
      scale_x_date(date_labels = "%d - %b", 
                   breaks = seq(min(small_data$date), max(small_data$date), by = 1)) +
      theme(axis.text.x = element_text(angle = 65, hjust = 1))
    

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      相关资源
      最近更新 更多