I am trying to increase the size of the margins of a common legend built when using ggarrange. I could increase the width of the plot, but I do not really want to do that. What do you suggest?
data1_df = data.frame(x = 1:4, y = 5e-6, type = 'type1')
data2_df = data.frame(x = 1:4, y = 6e-6, type = 'type2')
data3_df = data.frame(x = 1:4, y = 8e-6, type = 'type3')
data4_df = data.frame(x = 1:4, y = 9e-6, type = 'type4')
dataDF = NULL
dataDF = rbind(dataDF,data1_df)
dataDF = rbind(dataDF,data2_df)
dataDF = rbind(dataDF,data3_df)
dataDF = rbind(dataDF,data4_df)
for(i in 1:4){
plotG = ggplot(dataDF,aes(x = x, y = y, color = type, shape = type))+
geom_line(aes(group = type),show.legend = F)+
geom_point(aes(group = type),size = 3)+
scale_color_manual(breaks = c("type1","type2","type3","type4"),
values = c("darkorange3","lightblue3","skyblue1","dodgerblue3"))+
scale_shape_manual(breaks = c("type1","type2","type3","type4"),
values = c(3,16,17, 18))+
xlab('test')+ylab('Slope (= 1/4 * Va)')+
theme_bw()+ggtitle('Time 3')+
guides(color = guide_legend(byrow = TRUE), shape = guide_legend(byrow = TRUE))+
theme(legend.key.spacing.y = unit(0.5, "cm"))
assign(paste0('plot',i),plotG)
}
final_plot = ggarrange(print(plot1), print(plot2), print(plot3),print(plot4), labels = c("A","B","C","D"), ncol = 2, nrow = 2,common.legend = TRUE,legend = 'right')
You can increase the margins around the legend box using the legend.box.margin
theme option:
library(ggplot2)
library(ggpubr)
for (i in 1:4) {
plotG <- ggplot(dataDF, aes(x = x, y = y, color = type, shape = type)) +
geom_line(aes(group = type), show.legend = F) +
geom_point(aes(group = type), size = 3) +
scale_color_manual(
breaks = c("type1", "type2", "type3", "type4"),
values = c("darkorange3", "lightblue3", "skyblue1", "dodgerblue3")
) +
scale_shape_manual(
breaks = c("type1", "type2", "type3", "type4"),
values = c(3, 16, 17, 18)
) +
xlab("test") +
ylab("Slope (= 1/4 * Va)") +
theme_bw() +
ggtitle("Time 3") +
guides(color = guide_legend(byrow = TRUE), shape = guide_legend(byrow = TRUE)) +
theme(
legend.key.spacing.y = unit(0.5, "cm"),
legend.box.margin = margin(l = 2, r = 2, unit = "cm")
)
assign(paste0("plot", i), plotG)
}
ggarrange(print(plot1), print(plot2), print(plot3), print(plot4), labels = c("A", "B", "C", "D"), ncol = 2, nrow = 2, common.legend = TRUE, legend = "right")