2017-09-22 6 views
0

ggplot2で棒グラフを描画します(すでに長い形式で表示されています)。変数の値は、geom_text()ディレクティブを介してバーの中央に配置されます。R:変数の組み合わせを含むテキストをggplotに配置する

stuff.dat<-read.csv(text="continent,stuff,num 
America,apples,13 
America,bananas,13 
Europe,apples,30 
Europe,bananas,21 
total,apples,43 
total,bananas,34") 

library(ggplot2) 
ggplot(stuff.dat, aes(x=continent, y=num,fill=stuff))+geom_col() + 
     geom_text(position = position_stack(vjust=0.5), 
       aes(label=num)) 

今ではF =りんご/バナナのように定義された「アップル・バナナ指数」は、バーの上に追加する必要がある - と同じように、手動で、図に追加しました。これをggplotでどのようにプログラムするのですか?それを凡例に別のエントリとしてどのように追加することができますか?

simple stacked bar chart

+0

:これは可能な解決策とは?この数字は把握するのが難しく、この追加情報が必要になります – PoGibas

答えて

1

私はこれを達成する最も簡単な方法は、あなたがプロットを作成する前にデータを準備することだと思います。私は大陸与えstuff.datからリンゴ・バナナ・インデックスを計算する関数abi()定義:

abi <- function(cont) { 
    with(stuff.dat, 
     num[continent == cont & stuff == "apples"]/num[continent == cont & stuff == "bananas"] 
) 
} 

をそして私は必要なすべてのデータをデータフレームを作成します。私ができる、今

conts <- levels(stuff.dat$continent) 
abi_df <- data.frame(continent = conts, 
        yf = aggregate(num ~ continent, sum, data = stuff.dat)$num + 5, 
        abi = round(sapply(conts, abi), 1)) 

プロットにその情報を追加します。

library(ggplot2) 
ggplot(stuff.dat, aes(x = continent, y = num, fill = stuff)) + 
    geom_col() + 
    geom_text(position = position_stack(vjust = 0.5), aes(label = num)) + 
    geom_text(data = abi_df, aes(y = yf, label = paste0("f = ", abi), fill = NA)) 

enter image description here

fill = NAを追加するとハックが発生し、警告が表示されます。しかし、fillが設定されていない場合、プロットは失敗し、stuffが見つからないというメッセージが表示されます。私もfill = stuffggplot()からgeom_col()に移動しようとしましたが、これはバーの中のテキストラベルのy座標を壊します。これにはよりクリーンな解決策があるかもしれませんが、私はそれをまだ見つけていません。

追加の凡例を追加することは残念ながら、プロット領域の外にテキストを簡単に追加できないため、些細なことではありません。これには実際には2つのステップが必要です。最初にannotation_custom()を使用してテキストを追加します。テキストを表示するには、クリッピングをオフにする必要があります(たとえば、hereを参照)。あなたは、通常のバープロットは、そのテキストを必要としないことを知っている

p <- ggplot(stuff.dat, aes(x = continent, y = num, fill = stuff)) + 
     geom_col() + 
     geom_text(position = position_stack(vjust = 0.5), aes(label = num)) + 
     geom_text(data = abi_df, aes(y = yf, label = paste0("f = ", abi), fill = NA)) + 
     guides(size = guide_legend(title = "f: ABI", override.aes = list(fill = 1))) + 
     annotation_custom(grob = textGrob("f: ABI\n(Apple-\nBanana-\nIndex", 
             gp = gpar(cex = .8), just = "left"), 
             xmin = 3.8, xmax = 3.8, ymin = 17, ymax = 17) 

# turn off clipping 
library(grid) 
gt <- ggplot_gtable(ggplot_build(p)) 
gt$layout$clip[gt$layout$name == "panel"] <- "off" 
grid.draw(gt) 

enter image description here

関連する問題