首页 > 解决方案 > 在水平图例标题的标题后添加换行符

问题描述

当 时theme(legend.position = "top"),图例是水平的并且可能有点太宽。

这是一个例子:


library(ggplot2)
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) + 
  geom_point() + 
  xlim(5,6) + 
  coord_fixed() +
  theme(legend.position = "top")

阴谋

reprex 包(v0.3.0)于 2021 年 1 月 14 日创建

为了减少图例的宽度,我想在“物种”标题后添加一个换行符。

我知道guides(guide_legend(ncol=2,nrow=2,byrow=TRUE)),它非常好,但会产生不同的输出。

标签: rggplot2legend

解决方案


我们可以使用in中的title.position参数:guide_legendscale_colour_discrete

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) + 
  geom_point() + 
  xlim(5,6) + 
  coord_fixed() +
  theme(legend.position = "top")+
  scale_colour_discrete(guide = guide_legend(title.position = "top"))

在此处输入图像描述


推荐阅读