Reputation: 1854
I am making a time series using bars in ggplot. For some reason the data isn't plotting for the first and last month. I think this is something to do with the limits - presumably the boundaries of the limits are excluded. However, when I extend the limits (so they go from December 2015 to January 2019 in this example), while there isn't any data for those months, the labels now start at December.
I introduced the limits originally because different plots were starting in different months (I don't know why - one was line and one was bar, so might be to do with different arguments, but still seemed odd to me). I want these to match, so thought having control over the limits would help. They do now match, but the bar version has the issues outlined.
I am looking for a solution where:
Here is my code:
library(ggplot2)
library(lubridate)
num_month <- seq(from = as.Date("2016-01-01"), to = Sys.Date(), by='month')
month_data <- as.data.frame(matrix(0, ncol = 0, nrow = length(num_month)))
month_data$month <- as.POSIXct(num_month)
month_data$freq <- sample(100, size = nrow(month_data), replace = TRUE)
today <- as.POSIXct(Sys.Date())
date_lims <- c(as.POSIXct("2016-01-01", format = "%Y-%m-%d"), today)
ggplot(month_data, aes(x = month, y = freq)) +
geom_bar(stat = "identity") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12)) +
scale_x_datetime(labels = date_format("%b-%y"), breaks = date_breaks("2 months"),
limits = date_lims)
Here is what it looks like:
Thanks for your help!
Upvotes: 3
Views: 284
Reputation: 67040
ggplot(month_data, aes(x = month, y = freq)) +
geom_bar(stat = "identity") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12)) +
scale_x_datetime(date_labels = "%b-%y", date_breaks = "2 months",
limits = date_lims, expand = c(0,0))
This seems to work for me. I think the expand = c(0,0)
part is what you were missing; this tells ggplot not to add any padding to the sides, as is default.
Upvotes: 1