I cannot seem to fix this bar graph so the bars don't go over the axis. I've limited the axis to the minimum date i want, but I think that's what's causing the issue. I hope someone can help. Thank you!
My code:
ggplot(rreasont, aes(x = Week, y = count, color = reason, fill = reason)) geom_bar(stat = "identity", position = "fill", width = 5)
scale_color_manual(values = mycolors) scale_fill_manual(values = mycolors) labs(y = "Tests Linked to Reason") theme_linedraw() facet_wrap(~Contractor)
scale_x_date(breaks = (as.Date(rreasont$Week)), date_labels = "%m/%d")
theme(legend.position = "bottom", axis.title = element_text(size = 30), axis.text = element_text(size =25),
legend.text = element_text(size = 18), legend.title = element_blank(), strip.text = element_text(size = 25))
coord_cartesian(xlim = as.Date(c(min(ymd("2022-01-24")), max(rreasont$Week)))) #limit min date!
ggsave(paste(savef, "new_reason_for_testing_over_time.png", sep = ""), width = 23, height= 9)
CodePudding user response:
There are a few things that will give you more breathing room between your bars and the ends of the x axis — which I think is what you’re asking?
First, reduce the relative width of your bars; width = 5
means each bar takes up 5 times the width of the corresponding date on the x axis, which causes it to run off the graph.
Second, you can add space to the x axis either by expanding the limits by a few days in either direction, or with the expand
argument to scale_x_date()
.
plot
scale_x_date(expand = expansion(mult = .1))
# experiment with different values of “mult.”
# see ?expansion for more details
Third, you may get more intuitive spacing by first filtering your data to include only the dates you want, then plotting, and omitting coord_cartesian()
.