ggplot在刻面时删除特定的x轴标签

时间:2019-06-25 18:00:49

标签: r ggplot2

library(tidyverse)
set.seed(200)
df <- tibble(Date = seq(as.Date("2018/1/1"), by = "month", length.out = 16),
             Year = c(rep("2018", 12), rep("2019", 4)), 
             Values = c(runif(16, 20, 80)))

ggplot(df, aes(Date, Values)) + 
  geom_line() + 
  scale_x_date(breaks = "month", 
               date_labels = "%b",
               expand = expand_scale(add = c(31, 31))) +
  facet_grid(~Year, scales = "free_x", space = "free_x")

如何删除标记我的x轴的不必要月份?

  • DecJan在我的2018年情况下
  • DecMay在我的2019年构想中

我玩过breaks = df$Date之类的游戏,但这破坏了我的自由缩放和刻面上的自由间距(对双关语)。 并且我需要保留expand参数,我想要额外的空间,而不是随之而来的额外月份标签。

我得到的东西 extra ggplot x axis months

我想要的 extra ggplot x axis months removed

2 个答案:

答案 0 :(得分:2)

如果您希望对标签进行太多控制,则应传递自己的标签功能。这是一种可行的方法。我们基本执行ggplot的默认操作,然后将第一个/最后一个非NA值替换为长度为零的字符串以隐藏标签

ggplot(df, aes(Date, Values)) + 
  geom_line() + 
  scale_x_date(breaks = "month", 
               labels = function(x) {
                 lab <- scales::date_format("%b")(x)
                 lab[range(which(!is.na(lab)))] <- ""
                 lab
                },
               expand = expand_scale(add = c(31, 31))) +
  facet_grid(~Year, scales = "free_x", space = "free_x")

enter image description here

答案 1 :(得分:0)

您可以尝试将代码修改为

set.seed(200)
df <-
  tibble(
    Date = seq(as.Date("2018/1/1"), by = "month", length.out = 14),
    Year = c(rep("2018", 12), rep("2019", 4)),
    Values = c(runif(16, 20, 80))
  )

ggplot(df, aes(Date, Values)) +
  geom_line() +
  scale_x_date(breaks = "month",
               date_labels = "%b",) +
  facet_grid(. ~ Year, scales = "free", space = "free")

a better visualization of what you want**

或者您可以将expand参数编辑为减号;删除填充,这将删除您不想显示的多余月份

  scale_x_date(breaks = "month", 
                    date_labels = "%b",
                 expand = expand_scale(add = -1))

The same chart without unneeded months