ggplot2中每个图例标签的多行文本

时间:2017-11-01 19:45:13

标签: r ggplot2 legend

我正在尝试在条形图中处理很长的标签(见图片和我用来制作它的代码。我需要在多行(行)中分解它们(2或3行) ),另一方面,整个画面将是广泛的。一些帮助将是非常有帮助的。实际上我也怀疑我的代码不是应该如此简洁,但至少它有效(但随意改变)

enter image description here

glimpse(df)

Observations: 301
Variables: 3
$ V12n     <int> 1, 4, 4, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1...
$ V12      <fctr> De verwijzer neemt contact op om na te gaa...
$ METING.f <fctr> Meting 0, Meting 0, Meting 0, Meting 0, Me...

p = ggplot(df, aes(x = V12n, fill = V12)) + 
 geom_bar(aes(y = (..count..)/tapply(..count..,..PANEL..,sum)
 [..PANEL..])) + 
 scale_y_continuous(labels = scales::percent) + 
 geom_text(aes(y = ((..count..)/sum(..count..)), 
               label = scales::percent((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..])), 
               stat = "count", vjust = -0.25) +
 facet_grid(.~ METING.f) +
 labs(title = " ",
   x = "Vraag 12",
   y = "Percentage")  +
 theme(axis.text.x = element_blank(),
       axis.ticks.x=element_blank()) +
 scale_fill_manual(values = c("greenyellow", "green4", "darkorange1", "red"), 
                name = "Zijn er afspraken gemaakt over het overdragen van de verantwoordelijkheid naar de volgende zorgverlener?\n") 

 p

1 个答案:

答案 0 :(得分:14)

您可以使用str_wrap自动换行长字符串,也可以通过将\n(换行符)添加到字符串来进行硬编码。要在图例键之间添加空格,可以使用legend.key.height主题元素。以下是内置iris数据框的示例:

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

enter image description here