Multiple Lines for Text per Legend Label in ggplot2

我们两清 提交于 2019-11-29 01:48:15

You can use str_wrap for automated wrapping of long strings or you can hard code breaks by adding \n (the line break character) to a string. To add space between the legend keys, you can use the legend.key.height theme element. Here's an example with the built-in iris data frame:

library(stringr)
library(tidyverse)

# Create long labels to be wrapped
iris$Species = paste(iris$Species, 
                     "random text to make the labels much much longer than the original labels")

ggplot(iris, aes(Sepal.Length, Sepal.Width, colour=str_wrap(Species,20))) +
  geom_point() +
  labs(colour="Long title shortened\nwith wrapping") +
  theme(legend.key.height=unit(2, "cm"))

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