ggplot2:如何向水平图例添加换行符

use*_*439 0 r legend ggplot2

请考虑以下 R 脚本(取自此处并稍作修改):

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
Run Code Online (Sandbox Code Playgroud)

图例显示在图的顶部。我想把这个图例分成两行,每行有两个键。这可能吗?

请注意,如您所见,我已经尝试过

p+guides(guide_legend(ncol=2,nrow=2,byrow=TRUE))
Run Code Online (Sandbox Code Playgroud)

正如此处此处所建议的那样,但它对我不起作用。此建议基本上显示线性和多项式模型的数据和图例,并完全隐藏对数和指数模型。

Mat*_*att 7

正如eipi10所解释的,

您需要指定哪个图例,在本例中为颜色图例: guides(colour=guide_legend(ncol=2,nrow=2,byrow=TRUE)).

澄清一下,审美是定义colour每条线的。如果fill使用,则该行可以是guides(fill=guide_legend(ncol=2,nrow=2,byrow=TRUE))