I am trying to set the limits of a geom_col()
plot to include only specific dates. However, when I attempt to set the limit with scale_x_date()
the bars for the end points disappear. If the end points are moved, the new end points disappear.
library(ggplot2)
TestData <- data.frame(
"Date" = as.Date(c('2020-10-16','2020-10-17','2020-10-18', '2020-10-19', '2020-10-20')),
"Number" = c(5,3,2,4,1)
)
ggplot(TestData, aes(x = Date, y = Number, fill = 'red', col = 'white')) +
geom_col() +
scale_x_date(limits = as.Date(c('2020-10-17','2020-10-19'))) +
geom_text(aes(label=Number), vjust = -0.5) +
ylim(0,15)
The above MWE generates the plot below.
The same issue occurs regardless of whether I use xlim()
or scale_x_date()
.
I agree the best way to deal with this is to filter your data. You can do this with dplyr
library(dplyr)
TestData %>%
filter(Date>='2020-10-17' & Date<='2020-10-19') %>%
ggplot(aes(x = Date, y = Number, fill = 'red', col = 'white')) +
geom_col() +
geom_text(aes(label=Number), vjust = -0.5) +
ylim(0,15)
You could also technically do it with a scale but it's kind of a hack. You just need to adjust the end points a bit to filter out the other geoms to make sure they get dropped.
ggplot(TestData, aes(x = Date, y = Number, fill = 'red', col = 'white')) +
geom_col() +
scale_x_date(limits=as.Date(c('2020-10-17','2020-10-19')) + c(-.5, .5)) +
geom_text(aes(label=Number), vjust = -0.5) +
ylim(0,15)
This still generates a warning message about the dropped values.