簡體   English   中英

ggplot2中每個圖例標簽的多行文本

[英]Multiple Lines for Text per Legend Label in ggplot2

我正在嘗試處理條形圖中的圖例的非常長的標簽(請參見隨附的圖片以及我用來生成該圖例的代碼。我需要將它們分解為多行(2行或3行),其他明智的做法是寬泛地看一下。有些幫助會非常有幫助。實際上,我還懷疑我的代碼不夠簡潔,但至少可以正常工作(但可以隨時更改)

在此處輸入圖片說明

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM