2017-11-14 9 views
1

boxplotシンボルを表示する代わりに、凡例にa1(ランダム)、a2(ランダム2)、a3(ランダム3)を表示するにはどうすればよいですか?ggplot2のboxplotの凡例のテキストを定義する

The plot is here

私が働いているコードは

library(ggplot2) 
library(reshape2) 

B <- 25 
datainit <- data.frame(v1 = 1:B, a1 = randl, a2 = rand2, a3 = rand3) 
idinit <- rep(c('a1', 'a2', 'a3'), each = B) 
dat.minit <- melt(datainit, id.vars=idinit, measure.vars=c('a1', 'a2', 'a3')) 
position <- c('a1', 'a2', 'a3') 

plegend <- ggplot(dat.minit, aes(x = idinit, y = value, fill = idinit)) + 
geom_boxplot(fill='white',color="darkred", show.legend = TRUE, width = 0.4) +  
stat_boxplot(geom = "errorbar", width = 0.5, color="darkred") + 
labs(x = "methods", y = "values") + 
scale_x_discrete(limits = position) + 
scale_fill_discrete(name="some\nmethods", 
    labels=c('random', 'random 2', 'random 3')) 

あるデータは

v1  a1  a2  a3 
1 1 0.6715123 0.6851999 0.6858062 
2 2 0.6123710 0.6330409 0.6317203 
+0

おそらく 'geom_text'はこれの凡例よりも使いやすくなります。または、従来より、図形自体ではなく、図のキャプションにカテゴリの追加の説明を追加します。 – dww

+0

すでにx軸にグループが表示されています。冗長になるので、いつでもラベルを変更して凡例を削除することができます。 –

+0

はい、私は気付いていますが、名前の一部が大きすぎてx軸に表示できません。 –

答えて

1

のようなオプションがの構造に掘るためにgridコマンドを使用することができ一つであります凡例を入力し、ボックスプロットキーをa1、a2、a3に置き換えます。

library(ggplot) 
library(grid) 

plegend <- ggplot(dat.minit, aes(x = idinit, y = value, fill = idinit)) + 
    geom_boxplot(fill='white',color="darkred", show.legend = TRUE, width = 0.4)  + 
    stat_boxplot(geom = "errorbar", width = 0.5, color="darkred") + 
    labs(x = "methods", y = "values") + 
    scale_x_discrete(limits = position) + 
    scale_fill_discrete(name="some\nmethods", 
    labels=c('random', 'random 2', 'random 3')) 

# Get the plot grob 
g = ggplotGrob(plegend) 

# Get the legend 
leg = g$grobs[[which(g$layout$name == "guide-box")]] 

# Get the positions of keys in the legend layout 
pos = grep("key-[0-9]+-1-1", leg$grobs[[1]]$layout$name) 

# Get the labels 
label = c("a1", "a2", "a3") 

# Replace the keys with the labels 
for(i in seq_along(pos)) { 
    leg$grobs[[1]]$grobs[[pos[i]]] = textGrob(label[i], gp = gpar(cex = .75)) 
    } 

# Put the legend back into the plot 
g$grobs[[which(g$layout$name == "guide-box")]] = leg 

# Draw it 
grid.newpage() 
grid.draw(g) 
+0

ブリリアント、ありがとう! –

+0

10個のボックスプロットがある場合、このコードはposで設定されている最初の7個のラベルを変更するだけです。だから基本的にキーを設定する方法は? @Sandy –

+0

@ファチマバトゥール。ポジションを選ぶラインのRegExが問題でした。 '。'選択された1文字。 7つ以上のキーがある場合、RegExは1つまたは2つの文字を選択する必要があります。やってみよう。修正する必要があります。 –

関連する問題