ggplot2: How to add linebreak to horizontal legend

2019-09-15 04:28发布

问题:

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.

回答1:

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)).



标签: r ggplot2 legend