在ggplot2中裁剪第一个和最后一个标签

3

我有一个按天统计两种类型数据的图表,我想要去掉图表的第一个和最后一个标签。下面是可重现的数据示例:

library(dplyr)
library(ggplot2)
library(scales)
dates <- paste0("2014-01-", 1:31)
dat <- data.frame("Date" = sample(dates, 4918, replace=T), 
                  "Type" = sample(c('Type1', 'Type2'), 4918, replace=T, probs=c(.55, .45)))

p.data <- dat %>% group_by(Date, Type) %>% summarise(Freq = n())
p.data$Date <- as.Date(p.data$Date)

这是绘图的代码:

p <- ggplot(data=p.data, aes(x=Date, y=Freq, fill=Type)) + 
              geom_bar(stat='identity', position='dodge') +
              labs(x='Date', y='Count', title='Frequency of Data by Day') + 
              theme_bw() + 
              theme(axis.text.x = element_text(angle=90),
                    panel.grid.minor = element_blank(),
                    plot.title = element_text(vjust=1.4),
                    legend.position='bottom') + 
              scale_x_date(labels=date_format("%a %d"), 
                           breaks=date_breaks("day"), 
                           limits=c(as.Date('2014-01-01'), as.Date('2014-01-31'))) + 
              scale_y_continuous(limits=c(0, 150), breaks=seq(from=0, to=150, by=25)) + 
              scale_fill_manual(values=c('dark grey', 'light green'))

正如您所看到的,月初前一天和月末后一天有两个标签点。我该如何去除它们?我能否在scale_x_date()中仅选用标签和断点呢?

1个回答

3
scale_x_date中,expand参数是一种实现的方法。它会尝试通过在边缘周围增加一些额外的空间来提供帮助,但在这种情况下它增加了超过一天的时间,因此轴标签上有这些额外的天数。
p <- ggplot(data=p.data, aes(x=Date, y=Freq, fill=Type)) + 
              geom_bar(stat='identity', position='dodge') +
              labs(x='Date', y='Count', title='Frequency of Data by Day') + 
              theme_bw() + 
              theme(axis.text.x = element_text(angle=90),
                    panel.grid.minor = element_blank(),
                    plot.title = element_text(vjust=1.4),
                    legend.position='bottom') + 
              scale_x_date(labels=date_format("%a %d"), 
                           breaks=date_breaks("day"), 
                           limits=c(as.Date('2014-01-01'), as.Date('2014-01-31')),
                           expand=c(0, .9)) + 
              scale_y_continuous(limits=c(0, 150), breaks=seq(from=0, to=150, by=25)) + 
              scale_fill_manual(values=c('dark grey', 'light green'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接