虽然使用ggplot2生成图形,但我有一些很长的图例名称,我希望用两行代码。例如:
a <- (1:10)
b <- c(1,1.5,2,4,5,5.3,7,9,9.5,9.8)
places = c("Birmingham","Chester-le-street","Cambridge", "Newcastle-upon-Tyne","Peterborough","Cambridge", "Newcastle-upon-Tyne","Peterborough","Liverpool","Stratford-upon-Avon")
df1 = data.frame(a,b,places)
library(ggplot2)
i = ggplot(df1, aes(x=a, y=b)) + geom_point(aes(colour = places), size=3) + opts(legend.position="bottom")
如果将框设置在底部,我将如何包装图例项目 - 例如2行或3行?目前,传奇的七个项目彼此相邻。我希望它们显示在两行中(比如顶行的四个城镇和第二行的三个城镇)。
非常感谢提前。
答案 0 :(得分:28)
好的,根据你的编辑,你可能想要这个:
library(scales)
i + guides(colour = guide_legend(nrow = 2))
但你可能会发现你仍然想要使用文本包装技术,以使其适合。
答案 1 :(得分:20)
从你的例子:
df1$places<-sub("-", "- \n ", df1$places)
i = ggplot(df1, aes(x=a, y=b)) + geom_point(aes(colour = places), size=3)
注意: - 您可以使用gsub将所有“ - ”替换为“ - \ n”
答案 2 :(得分:2)
另一种包装图例标签的方法(我发现非常方便)是以下这些(全部记入https://sites.google.com/site/simonthelwall/home/r/ggplot2#TOC-Wrapping-legend-labels):
a <- (1:10)
b <- c(1,1.5,2,4,5,5.3,7,9,9.5,9.8)
places = c("Birmingham","Chester-le-street","Cambridge", "Newcastle-upon-Tyne","Peterborough","Cambridge", "Newcastle-upon-Tyne","Peterborough","Liverpool","Stratford-upon-Avon")
df1 = data.frame(a,b,places)
library(ggplot2)
i = ggplot(df1, aes(x=a, y=b)) + geom_point(aes(colour = places), size=3)
i + scale_colour_discrete(labels = function(x) str_wrap(x, width = 5))