scale_x_date 删除轴上的额外月份(ggplot2 2.2.0.9)

Mon*_*uiz 4 r ggplot2

我使用的是带有时间刻度的折线图,最后一点是 12 月 30 日。但是,对于scale_x_date,即使有该月的数据点,一月也会显示在刻度上。

规模确实应该在上个月停止,但我相信这是因为这一天。有没有办法让刻度坚持数据中的实际月份?

我用它来格式化比例:

#with lubridate
data$month <- ymd(data$month)

#in the plot
scale_x_date(date_breaks = "1 month", date_labels ="%b %y")
Run Code Online (Sandbox Code Playgroud)

可重现的例子:

library(lubridate)
library(ggplot2)

cities <- c("city1")
month <- c("2016-08-01", "2016-09-30", "2016-10-30", "2016-11-30", "2016-12-30")
num <- c(23287, 23889, 25026, 26116, 29758)

data <- data.frame(cities, month, num)
data$month <- ymd(data$month)

gg <- ggplot(data, aes(month, num, group = 1)
gg <- gg + geom_line(position = "identity", color="#6baed6")
gg <- gg + scale_y_continuous(expand = (c(0.1,0)))
gg <- gg + scale_x_date(expand = c(0, 0), date_labels ="%b %y")
gg <- gg + labs(x = NULL, y = NULL)
gg <- gg + theme(strip.background=element_blank())
gg <- gg + theme_bw()
gg <- gg + theme(panel.border = element_blank())
gg <- gg + theme(panel.grid.major = element_blank())
gg <- gg + theme(panel.grid.minor = element_blank())
gg <- gg + theme(axis.ticks=element_blank())
gg <- gg + theme(axis.text.x=element_text(size=12))
gg <- gg + theme(axis.text.y=element_text(size=12))
gg
Run Code Online (Sandbox Code Playgroud)

在此示例中,如果没有 Expand(),即使一月没有数据点,也会添加一月。

每月有一个数据点,我的目标是按月显示数据。我可以转换为因子,但这并不理想。我知道数据有一天,但肯定有办法做到这一点。

Rol*_*and 6

我不认为这是一个好情节,但你就在这里。您可能希望将休息时间设置为每月 15 日:

library(ggplot2)
ggplot(data, aes(month, num, group = 1)) + 
  geom_line(position = "identity", color="#6baed6") + 
  #scale_y_continuous(expand = (c(0.1,0)), labels = comma) +
  scale_x_date(breaks = seq(as.Date("2016-07-15"), 
                            as.Date("2016-12-15"), by = "1 month"), date_labels ="%b %y") + 
  labs(x = NULL, y = NULL) + 
  theme_bw() +
  theme(strip.background=element_blank(),
        panel.border = element_blank(),
        panel.grid = element_blank(),
        axis.ticks=element_blank(),
        axis.text=element_text(size=12)) 
Run Code Online (Sandbox Code Playgroud)

结果图