2017-10-31 7 views
1

以下のコードでdfをプロットすると、各列のnを列自体の上に置くことができます。as seen in this example plot私がやりたいことは、ラベルに各列のパーセンテージを入れることです。これは、列が構成する合計の割合です。したがって、たとえば、最初の列のラベルは、127ではなく、127(42.9%)となります。どうすればいい?geom_col、ggplot2のnとパーセントラベル

df <- structure(list(Letter = structure(1:7, 
     .Label = c("A", "B", "C", "D", "E", "F", "G"), 
     class = "factor"), Freq = c(127L, 101L, 24L, 19L, 3L, 0L, 22L)), 
     .Names = c("Letter", "Freq"), 
     row.names = c(NA, -7L), 
     class = "data.frame") 

ggplot(df, aes(Letter, Freq, label = Freq)) + 
    geom_col() + 
    geom_text(size = 3, position = position_dodge(width = 1), vjust = -0.25) 

答えて

2

ラベルとして使用するテキストを作成してください。

df$pct = df$Freq/sum(df$Freq) * 100 
df$label = sprintf("%s (%s%%)", df$Freq, round(df$pct, 1)) 

ggplot(df, aes(Letter, Freq, label = label)) + 
    geom_col() + 
    geom_text(size = 3, position = position_dodge(width = 1), vjust = -0.25) 

enter image description here