gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:10:37 26 4
gpt4 key购买 nike

我正在尝试处理条形图中图例的非常长的标签(请参阅包含的图片和我用来生成它的代码。我需要将它们分解为多(行)行(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

最佳答案

您可以使用 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

关于r - ggplot2 中每个图例标签的多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47062532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com