Is there any way that I can create a completely custom legend that won\'t care about the aesthetics or anything else in my plot? I would like if possible to design everythin
I managed to plot what I wanted but in an ugly way when it comes to coding.
In short, I added different aesthetics until I got at least two legend groups with the desired number of elements and shapes. Then I used the scale_*_manual
functions and the guide()
function to override some of the aesthetics and make the legend look almost as it should (still I didn't manage to have a vertical line in a legend box).
The code is the following:
ggplot(a, aes(x = random, y = result)) +
geom_density2d(bins = 20) +
geom_point(aes(color = factor(multiplier2), shape = factor(multiplier2), fill = factor(multiplier2)), stroke = 0.01, size = 2.5) +
geom_vline(data = means, aes(xintercept = mean_rand, color = "mean_rand", size = "mean_rand"), show.legend = FALSE) +
geom_hline(data = means, aes(yintercept = mean_res, color = "mean_res", size = "mean_res"), linetype = 12, show.legend = FALSE) +
scale_color_manual(values = c(col[1], col[2], "orange", "red")) + # Provides the desired colors for the plot
scale_shape_manual(name = "Values", values = c(21, 22), labels = c("*0.1", "*0.3")) + # Provides the desired shape and plots the "Values" legend
scale_fill_manual(name = "Values", values = c(col[1], col[2]), labels = c("*0.1", "*0.3")) + # Provides the fill for the shapes and merges the legend with the shape ("Values") legend
scale_size_manual(name = "Averages", values = c(1.5, 1.5), labels = c("Random", "Result")) + # Provides a legend for the Averages but looks ugly.....
guides(color = FALSE, # Hides the "color" legend because it has 4 values and we don't want that.
shape = guide_legend(order = 1), # Forces the "Values" legend group to be on top
fill = guide_legend(order = 1), # Forces the "Values" legend group to be on top
size = guide_legend(order = 2, override.aes = list(linetype = c(1, 12), color = c("orange", "red")))) + # Makes the "Average" legend to look as it should, by overriding the aesthetics
facet_grid(~ multiplier) +
theme_dark() +
theme(panel.grid.major = element_line(colour = "white", linetype = "dashed", size = 0.2),
panel.background = element_rect(fill = "#555555"),
legend.key = element_rect(fill = "#555555"))
And that's how the result looks like: