2017-06-29 2 views
3

ggplot2によって生成されたboxplotの各ボックスの上にラベルを表示したいと思います。例えばggplot2 boxplotのラベルボックス

#Example data 
test = c("A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B") 
patient = c(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3) 
result = c(5, 7, 2 ,4, 6, 7, 3, 5, 5, 6, 2 ,3) 
data <- tibble(test, patient, result) 

#Labels I want to include 
Alabs = c(1, 3, 500) 
Blabs = c(8, 16, -32) 

#Plot data 
ggplot(data, aes(x = factor(patient), y = result, color = factor(test))) + 
    geom_boxplot(outlier.shape = 1) 

プロットを与える:

enter image description here

Iは最初の患者のための赤いボックス上記Alabsの最初の要素を印刷したい、の2番目の要素をAlabsの2番目の患者の赤いボックスの上に、最初の患者の青いボックスの上のBlabsの最初の要素など

どうすればいいですか?

答えて

1

私はラベルを追加するための独立したラベルデータセットになるだろう。

labs = tibble(test = rep(LETTERS[1:2], each = 3), 
        patient = c(1, 2, 3, 1, 2, 3), 
        labels = c(1, 3, 500, 8, 16, -32)) 

    test patient labels 
    <chr> <dbl> <dbl> 
1  A  1  1 
2  A  2  3 
3  A  3 500 
4  B  1  8 
5  B  2  16 
6  B  3 -32 

上記には、x軸とファセット変数に関するすべての情報が含まれています。欠けているのは、y軸上のテキストの位置に関する情報です。これらをボックスの上に置くには、各係数の組み合わせの最大値とyの位置の小さな値を計算することができます(geom_textは有用なnudge_y引数を持ちますが、覆い隠しでは機能しません)。

グループごとの要約をdplyrで行い、yの値をラベルデータセットに結合します。

library(dplyr) 

labeldat = data %>% 
    group_by(test, patient) %>% 
    summarize(ypos = max(result) + .25) %>% 
    inner_join(., labs) 

ラベルのデータセットを使用してgeom_textレイヤーを追加できます。ボックスプロットと同じ方法でこれらを避けるには、position_dodgeを使用します。伝説に手紙が現れないように、私はshow.legend = FALSEを使用します。

ggplot(data, aes(x = factor(patient), y = result, color = test)) + 
    geom_boxplot(outlier.shape = 1) + 
    geom_text(data = labeldat, aes(label = labels, y = ypos), 
       position = position_dodge(width = .75), 
       show.legend = FALSE) 

enter image description here

1

は同じtibbleにラベルを取得するために浮気いくつかを取ります。そして、

data$labs=c(NA, 1, NA, 3, NA, 500, NA, 8, NA, 16, NA, -32) #line up the labels so each patient gets one: if you put the NAs first, labels will be at the bottom of the boxes 
data$lab_x=c(NA, 0.75, NA, 1.75, NA, 2.75, NA, 1.25, NA, 2.25, NA, 3.25) #set x position for each one 

ggplotを実行します。

ggplot(data, aes(x = factor(patient), y = result, color = factor(test))) + 
    geom_boxplot(outlier.shape = 1)+ 
    geom_text(aes(label=labs, x=lab_x)) 

enter image description here

関連する問題