For my data the average normally lies between 8,000 and 10,000 and I want to indicate this range on my bar chart below, I want to show to red lines from y=10,000 and y=8,000 and potentially shade the area in between them, if possible. Bar chart attachted
Monthly_accidents2 %>%
ggplot(aes(x=Month,y=Traffic_Accidents))
geom_bar(stat ="identity",fill = "#97B3C6")
geom_text(aes(label = Traffic_Accidents), vjust = 0.5, colour = "white")
ylim(0,12000)
#coord_flip()
theme_dark()
labs(x=NULL,
y="Number of traffic accidents",
title = " Traffic Accidents throughout the year")
Thanks for any possible help in advance.
I tried creating a data set and adding the two lines but it didn't work.
CodePudding user response:
One option to achieve your desired result would be to use geom_hline
to add some horizontal lines and annotate
to add a shaded rectangle:
Using some fake example data:
Monthly_accidents2 <- data.frame(
Month = factor(month.abb, month.abb),
Traffic_Accidents = 1000 * seq_len(12)
)
library(ggplot2)
base <- ggplot(Monthly_accidents2, aes(x = Month, y = Traffic_Accidents))
geom_col(fill = "#97B3C6")
geom_text(aes(label = Traffic_Accidents), vjust = 0.5, colour = "white")
ylim(0, 12000)
theme_dark()
labs(
x = NULL,
y = "Number of traffic accidents",
title = "Traffic Accidents throughout the year"
)
theme(plot.title = element_text(hjust = .5))
base
geom_hline(yintercept = c(8000, 10000), color = "red")
annotate(geom = "rect", ymin = 8000, ymax = 10000, xmin = -Inf, xmax = Inf, fill = "red", alpha = .2)
CodePudding user response:
add the following to your plot:
geom_hline(aes(yintercept = c(8000, 10000), color = "red"))
For the lines
edit: See stefan's more complete answer.
CodePudding user response:
For adding the two lines, 'geom_hline' makes it very straightforward. And for the shaded area, you can use 'geom_rect', though I'm guessing your 'Month' variable is factor so it requires a little bit of faffing to convert it to numeric first then adjust so the shaded area covers all of your bars :)
You didn't provide any sample data so I haven't run this but it should work.
Monthly_accidents2 %>%
ggplot(aes(x=Month,y=Traffic_Accidents))
geom_bar(stat ="identity",fill = "#97B3C6")
geom_text(aes(label = Traffic_Accidents), vjust = 0.5, colour = "white")
ylim(0,12000)
geom_hline(yintercept = c(8000, 10000), colour = 'red')
geom_rect(aes(xmin = min(as.integer(Monthly_accidents2$Month)) - 0.5,
xmax = max(as.integer(Monthly_accidents2$Month)) 0.5,
ymin = 8000, ymax = 10000), alpha = 0.2, fill = 'darkred')
#coord_flip()
theme_dark()
labs(x=NULL,
y="Number of traffic accidents",
title = " Traffic Accidents throughout the year")