ggplot2: How to add linebreak to horizontal legend

匆匆过客 提交于 2019-12-12 04:34:53

问题


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



来源:https://stackoverflow.com/questions/42281067/ggplot2-how-to-add-linebreak-to-horizontal-legend

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!