My question has two parts. Below I've provided example data and the code to create a representative plot using ggplot
structure(list(x = c(2.93131952459005, 3.21275054434318, 1.36466997175509,
2.13626543532502, 1.45889556823722, 1.94598707699052, 0.719062322132357,
2.38139571953234, 2.37813367615963, 3.98126576880209), y = c(7.51581380181603,
9.77495763943671, 8.9666894018554, 8.62675858853528, 7.89238665417542,
9.84865061237773, 7.24526820962333, 7.64727218939944, 7.28026738945878,
8.6913070524479), z = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L,
3L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor"), z2 = structure(c(1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("cat", "dog"), class = "factor")), class = "data.frame", row.names = c(NA,
-10L))
ggplot(exampledata, aes(x = x, y = y, color = z, shape = z))+geom_point()+geom_line(aes(color = z, linetype = z2))+
scale_linetype_manual(values = c(1,2,3))+theme(legend.position = 'top')
Part 1: Changing legend size when multiple aesthetics exist.
When you look at the produced figure, item z in the legend has two aesthetics associated with it: color and shape. However, it refers to line color and not just point color/shape. I'm wondering if there is a way to increase the size of points (only in the legend) for z, while leaving the line size in z the same. I've tried override.aes()
with size as an argument but that increases the size for both points and lines.
Part 2: Increasing space between variables in the legend.
This should be pretty simple, but I haven't found a straightforward answer. Within the legend, z and z2 are obviously separate components, but is there a way to increase the space between these variables as a whole? I am not talking about increasing the space between each level of each variable like in legend.spacing.x
. Essentially I want more whitespace between the "c" from z and the title of z2.
To answer your part 1 question please see filups21 response to the following SO question ggplot2: Adjust the symbol size in legends. Essentially you need to change the underlying grid aesthetics with the following code.
# Make JUST the legend points larger without changing the size of the legend lines:
# To get a list of the names of all the grobs in the ggplot
g
grid::grid.ls(grid::grid.force())
# Set the size of the point in the legend to 2 mm
grid::grid.gedit("key-[-0-9]-1-1", size = unit(4, "mm"))
# save the modified plot to an object
g2 <- grid::grid.grab()
ggsave(g2, filename = 'g2.png')
The answer to part 2 is a little simpler, and only requires a small addition to the ggplot2 statement. Try adding the following: + theme(legend.spacing = unit(5, units = "cm"))
. And then play with the unit measurements until you get the desired look.