ggplot2:如何将换行符添加到水平图例 [英] ggplot2: How to add linebreak to horizontal legend

查看:484
本文介绍了ggplot2:如何将换行符添加到水平图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下R脚本(取自此处,并对其进行了稍微修改):

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.

推荐答案

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

为澄清起见,美学定义了每行的colour.如果使用fill,则该行可能是guides(fill=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)).

这篇关于ggplot2:如何将换行符添加到水平图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆