Trim first and last labels in ggplot2

拟墨画扇 提交于 2020-01-04 06:31:20

问题


I've got a plot that is tabulating two types of data by day and I'm looking to just trim the first and last label from the plot. Here is a reproducible example of the data:

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)

Here is the code for the plot:

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'))

As you can see, there are two label points for the day prior to the beginning of the month and the day after the last day of the month. How do I trim those off? Can I just subset the labels and breaks call in scale_x_date()?


回答1:


The expand argument in scale_x_date is one way to do it. It tries to be helpful by making some extra space around the edges, but in this case it adds more than a day, so the axis labels have those extra days.

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'))


来源:https://stackoverflow.com/questions/29100326/trim-first-and-last-labels-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!