修剪ggplot2中的第一个和最后一个标签 [英] Trim first and last labels in ggplot2
问题描述
我有一个阴谋,是白天列出两种类型的数据,我正在寻找修剪剧情的第一个和最后一个标签。这是一个可重现的数据示例:
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)
这是剧情的代码:
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()
?
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()
?
推荐答案
< p 在
参数是实现它的一种方法。它试图通过在边缘周围留出一些额外的空间来提供帮助,但在这种情况下,它会增加一天以上的时间,所以轴标签会有这些额外的日子。 scale_x_date
中展开
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'))
这篇关于修剪ggplot2中的第一个和最后一个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!