2017-11-01 12 views
2

私はバープロットの凡例のために非常に長いラベルに対処しようとしています(写真とそれを生成するために使用したコードを参照してください。実際には私のコードは簡潔ではないと思われますが、少なくともそれは機能します(例えば、行の行(2,3))。しかしggplot2の凡例ごとのテキストの複数の行

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 
+2

まず、 'ライブラリ(stringr)'とstinrgrパッケージをロードします。そして、ggplot coceで 'fill = str_wrap(V12、width = 20)'を実行します(必要に応じて幅を調整します)。 'scale_fill_manual'では' name'に 'str_wrap'を使うこともできますし、改行したいところに' \ n'を入れるだけでも構いません。 – eipi10

+0

うわー、それは最初の 'fill = ...'で動作しますが、私は凡例のラベルの間にもう少し垂直なスペースしか必要としません(テキストはラベルから次のラベルまで垂直にぴったりと重なっています)。 –

+1

私は、あなたの質問のそれぞれの問題。 – eipi10

答えて

2

あなたは長い文字列の自動折り返しのためstr_wrapを使用することができます)に変更して自由に感じるか、ハードコードBRをすることができます文字列に\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

+0

私のバープロットはあなたの答えのためにほぼ完璧に見える、私は唯一の凡例のキーの順序を変更する、バーの同じ順序を表示するように、最後のビット? –

関連する問題