1

Please consider the following R script (taken and slightly modified from here):

require(ggplot2)

x <- 1:10
y <- jitter(x^2)

DF <- data.frame(x, y)

p <- ggplot(DF, aes(x = x, y = y)) + geom_point() +
  stat_smooth(method = 'lm', aes(colour = 'linear')) +
  stat_smooth(method = 'lm', formula = y ~ poly(x,2), 
              aes(colour = 'polynomial')) +
  stat_smooth(method = 'nls', formula = y ~ a * log(x) +b, 
              aes(colour = 'logarithmic')) +
  stat_smooth(method = 'nls', formula = y ~ a*exp(b *x), 
              aes(colour = 'Exponential')) +
  theme(legend.position = "top") 

p <- p + guides(guide_legend(ncol=2,nrow=2,byrow=TRUE))


p

The legend is displayed at the top of the plot. I want to break this legend into two lines, with two keys in each line. Is this possible?

Please note that, as you may see, I already tried

p+guides(guide_legend(ncol=2,nrow=2,byrow=TRUE))

as suggested here and here, but it did not work for me. This suggestion basically displays the data and the legends of the linear and polynomial models and completely hides the logarithmic and exponential models.

Community
  • 1
  • 1
  • 3
    You need specify which legend, in this case the `colour` legend: `guides(colour=guide_legend(ncol=2,nrow=2,byrow=TRUE))`. However, when I run your code, `stat_smooth` fails for the `nls` models, so the space for the second row of the legend is created, but no legend boxes are actually rendered for the `nls` models. – eipi10 Feb 16 '17 at 17:51
  • @eipi10 this really works; thanks, but what if I have an odd number of keys, and I want the each row of the legend to be center-aligned horizontally. Is this possible? – user8420488483439 Feb 16 '17 at 19:59

1 Answers1

8

As explained by eipi10,

You need specify which legend, in this case the colour legend: guides(colour=guide_legend(ncol=2,nrow=2,byrow=TRUE)).

To clarify, the aesthetic is defining the colour of each line. If fill were used, the line could be guides(fill=guide_legend(ncol=2,nrow=2,byrow=TRUE)).

Matt
  • 490
  • 8
  • 19