I'm working on recreating some plots I used to do with Numbers (Mac) in R for efficiency and automation purposes.
I would like to achieve something like the following:
With some help I was able to set the distance between the legend and plot itself and also wrote a function to plot (see this post for more information).
Now I am stuck with the trendlines and am facing the following problem:
How can I force geom_smooth()
to start and end with the bar of the group the trendline belongs to? Default seems to be, that all trendlines start and end in the middle of the groups.
My current plot looks like this:
And here is a MWE to reproduce the main/relevant parts of the plot:
library(tidyverse)
set.seed(9)
data <- data.frame(Cat=c(rep("A",times=5),rep("B",times=5),rep("C", times=5)),
year=rep(c(2015,2016,2017,2018,2019),times=3),
count=c(sample(seq(60,80),replace=TRUE,size=5),sample(seq(100,140),replace=TRUE,size=5),sample(seq(20,30),replace=TRUE,size=5)))
legend_labels <- c("A","B","C")
ggplot(data=data,aes(x=year, y=count, fill=Cat)) +
geom_col(position="dodge",show.legend=TRUE) +
geom_smooth(aes(color=Cat),method="lm", formula=y~x,se=FALSE,show.legend=TRUE,linetype="dashed") +
scale_fill_manual(values = c("#CF232B","#942192","#000000"),labels=legend_labels) +
scale_color_manual(values= c("#CF232B","#942192","#000000"),labels=paste("Trend ",legend_labels,sep="")) +
theme(panel.background = element_rect(fill="white"),
legend.title = element_blank(),
legend.key = element_rect(fill="white")) +
guides(color=guide_legend(override.aes=list(fill=NA)),fill=guide_legend(override.aes = list(linetype=0)))
Note: Since I don't think they're relevant to the problem a lot of adjustment and user functions are not represented in this MWE.