I have this data frame and I'm trying to create a stacked bar with a line that goes through the middle.
my_df <- tibble(
Week = c(ymd("2022-06-06"),ymd("2022-06-06"),ymd("2022-06-06"),ymd("2022-06-06") 7,ymd("2022-06-06") 7, ymd("2022-06-06") 7),
Scenario = c("Conservative","Likely","Aggressive","Conservative","Likely","Aggressive"),
Hours = c(100,50,35,150,65,25),
Capacity = c(110,110,110,110,110,110)
)
ggplot(my_df, aes(fill=factor(Scenario, levels = c("Conservative","Likely","Aggressive")), y=Hours, x= Week, label = Hours))
geom_bar(position="stack", stat="identity")
geom_line(data = my_df, aes(x= Week, y = Capacity))
theme(
legend.title= element_blank()
)
Everything is technically "correct," but I want to extend the line to the edges of the graph because it will look better.
Here are the variations I've tried but nothing has worked to extend the Capacity line, which is the only thing I want to extend:
ggplot(my_df, aes(fill=factor(Scenario, levels = c("Conservative","Likely","Aggressive")), y=Hours, x= Week, label = Hours))
geom_bar(position="stack", stat="identity")
geom_line(data = my_df, aes(x= Week, y = Capacity))
theme(
legend.title= element_blank()
)
scale_x_date(extendrange(my_df$Week), expand = expansion(mult = c(0, .1)))
And I tried coord_cartesian.
ggplot(my_df, aes(fill=factor(Scenario, levels = c("Conservative","Likely","Aggressive")), y=Hours, x= Week, label = Hours))
geom_bar(position="stack", stat="identity")
geom_line(data = my_df, aes(x= Week, y = Capacity))
theme(
legend.title= element_blank()
)
coord_cartesian(xlim = c(ymd("2022-06-01"),ymd("2022-06-21")))
Ideally, I'd like to use something like the scale_x_date option because I need to run this report weekly and don't want to manually specify date limits. But either way neither of these options is extending the line.
CodePudding user response:
You can use geom_hline()
instead of geom_line()
.
ggplot(my_df, aes(fill=factor(Scenario, levels = c("Conservative","Likely","Aggressive")), y = Hours, x = Week, label = Hours))
geom_bar(position = "stack", stat="identity")
geom_hline(mapping = aes(yintercept = Capacity))
theme(legend.title = element_blank())