library(viridis) #loads the viridis color palette used in this script (must be installed the first time by install.packages("viridis")) library(ggplot2) #dataframe ID <- 1:750 values <- c(rnorm(150, mean=25, sd=5), rnorm(150, mean=22, sd=3), rnorm(150, mean=30, sd=4), rnorm(150, mean=15, 3), rnorm(150, mean=40, sd=5)) groups <- c(rep("A", 150), rep("B", 150), rep("C", 150), rep("D", 150), rep("E", 150)) df <- data.frame(ID, groups, values) #install and activate viridis install.packages("viridis") #run this once if viridis has never been used on your machine library(viridis) #run every time you start R/Rstudio #boxplot with colors and automatic legend stored in baseplot baseplot <- ggplot(df, aes(groups, values, fill=groups)) + geom_boxplot() + scale_fill_viridis(discrete=TRUE) baseplot #changing the legend position to a different side baseplot + theme(legend.position="bottom") #removing the legend baseplot + theme(legend.position="none") #putting the legend wherever you want baseplot + theme(legend.position = c(0.86, 0.2)) #changing the legend layout to horizontal baseplot + theme(legend.position = c(0.86, 0.05), legend.direction = "horizontal") #changing the internal layout of the legend baseplot + guides(fill= guide_legend(ncol = 2)) #changing the internal layout of the legend byrow baseplot + guides(fill= guide_legend(ncol = 2, byrow = TRUE)) #changing the title of the legend baseplot + labs(fill="New Title") #removing the title of the legend baseplot + theme(legend.title = element_blank()) #adjusting the title of the legend baseplot + theme(legend.title = element_text(face = "bold", color ="red", size=11)) #changing the colors of the legend baseplot + theme(legend.background = element_rect(fill = "lightblue", color = "red", size = 2))