15
votes

I'm plotting some data with R ggplot2. I have two variables that I'm plotting as a scatter plot, with two extra dimensions plotted as colour and shape. However, the plot doesn't work well with the legend outside (to small on the x-axis).

I moved the legend inside, but now the legend is to big! Is there a way to make it smaller that doesn't involve decrease the size of each individual component separately (legend title, legend labels, legend symbols)?

library(ggplot2)
p1  = ggplot(allPars, aes(x = log10(growthRate), y = log10(k), col = Background, shape = Timepoint))+
    geom_point(size = 2)+
    theme(legend.position = c(0.5,0.5))+
    xlab("Log10 Growth Rate")+
    ylab("Log10 K")
fig1 = plot_grid(p1, labels = "AUTO")
save_plot(filename = "~/projects/phd/Chapter4/fig4.pdf", plot = fig1, scale = 1)

enter image description here

2

2 Answers

25
votes

You have to decrease size of legend elements (overwrite passed parameters size =2) and decrease font size.

Create example plot with large legend

library(ggplot2)
p <- ggplot(mtcars, 
            aes(drat, mpg, color = factor(gear), shape = factor(vs))) +
        geom_point(size = 2) +
        theme_classic() +
        theme(legend.position = c(0.1, 0.7))

Decrease size of shape elements

# Overwrite given size (2) to 0.5 (super small)
p <- p + guides(shape = guide_legend(override.aes = list(size = 0.5)))

Decrease size of color elements

p <- p + guides(color = guide_legend(override.aes = list(size = 0.5)))

Decrease size of legend font

p <- p + theme(legend.title = element_text(size = 3), 
               legend.text = element_text(size = 3))

You can also write a custom function to modify your plots:

addSmallLegend <- function(myPlot, pointSize = 0.5, textSize = 3, spaceLegend = 0.1) {
    myPlot +
        guides(shape = guide_legend(override.aes = list(size = pointSize)),
               color = guide_legend(override.aes = list(size = pointSize))) +
        theme(legend.title = element_text(size = textSize), 
              legend.text  = element_text(size = textSize),
              legend.key.size = unit(spaceLegend, "lines"))
}

# Apply on original plot
addSmallLegend(p)

Final plot would look like this

enter image description here

1
votes

How about modifying the text size?

  theme(legend.title = element_text( size=2), legend.text=element_text(size=2))