I am currently using plot_model to plot a binomial generalized linear mixed effects model from an AIC model selection process. Overall, plot_model works well, but I am having trouble customizing the legend. This largely stems from the fact that some code needs to be within the plot_model function, while other code needs to be in the theme function. Here is my code and my current graph:
# generate break positions
breaks = c(seq(-30, 0, by=10), -2)
# and labels
labels = as.character(breaks)
plot1 <- plot_model(m2, type = "pred" ,
terms = c("Day [all]", "Sex"),
colors = c("blue", "red"),
ci.lvl = .95,
legend.title = "",
line.size = 1) +
labs(x = "Days Relative to Clutch Initiation", y = "P(Attend at night)", title = NULL) +
scale_x_continuous(expand = c(0, 0), breaks = breaks, labels = labels) +
scale_y_continuous(limit = c(0, 1), expand = c(0, 0)) +
theme_classic() +
theme(axis.text=element_text(size=16),
axis.title=element_text(size=14),
axis.title.x = element_text(vjust=-0.5),
axis.title.y = element_text(vjust=2.5),
axis.ticks.length=unit(0.1,"inch"),
legend.key.size = unit(1, 'cm'),
legend.position = "top",
legend.justification = "left",
plot.margin = margin(1,.5,1,1, "cm"))
plot1
I have a few aesthetic changes I would like to make to the legend:
Is it possible to change the colored icon next to "Males" and "Females" from the line in the box to a filled in box of that color? In other words, can I put a blue-filled box next to males, and a red-filled box next to females? If not, what other options do I have?
Would it be possible to stack the legend info over each other, so that "Males" is over "Females" instead of next to it?
Right now I am moving the orientation of the legend using legend.position and legend.justification. Is it possible to manually move the legend using coordinates? I would ideally like it a bit lower so it sits inside the graph.
How can I change the font size and type? I tried element_text, and maybe I did it wrong, but it didn't work. Ideally I would like it in Times New Roman (serif) and slightly larger.
I know this is a lot to ask, and if someone can point me in the right direction, I would greatly appreciate it. I am just having trouble with the formatting since the legend came as a result of the plot_model function, not through ggplot or another graphing package.
Try
#1)
plot1 + scale_fill_discrete(name = "Legend", labels = c("Males", "Females"))
#2)
plot1 + guides(fill=guide_legend(nrow=2,byrow=TRUE))
#3)
plot1 + theme(legend.position = c(x, y))
#4)
plot1 + theme(legend.text = element_text(colour="blue", size=10,
face="bold"))
But in my opinion, dont waste too many time with legend, one common way is to build nice and clear graphic with R then editing the legend under powerpoint.