ggplot2中每个图例标签的多行文本 [英] Multiple Lines for Text per Legend Label in ggplot2
问题描述
我正在尝试在条形图中处理非常长的图例标签(请参见随附的图片以及我用来生成该图例的代码.我需要将它们分解为多行(2行或3行) ),否则整个图片将变得很宽泛.有些帮助会非常有帮助.实际上,我还怀疑我的代码虽然不够简洁,但至少可以正常工作(但可以随时更改)
I'm trying to deal with very long labels for a legend in a bar plot (see picture included and the code i used to produce it. I need to break them down in multiple (rows of) lines (2 or 3), other wise the whole picture will be to wide. Some help would be very helpful. Actually I also suspect that my code is not as concise as it should be, but at least it works (but feel free to change)
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
推荐答案
您可以使用str_wrap
自动包装长字符串,也可以通过在字符串中添加\n
(换行符)来进行硬代码中断.要在图例键之间添加空格,可以使用legend.key.height
主题元素.这是内置iris
数据框的示例:
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"))
这篇关于ggplot2中每个图例标签的多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!