在ggplot2中为boxplot的图例定义文本

时间:2017-11-14 23:47:43

标签: r ggplot2 legend boxplot

如何在图例中显示a1(随机),a2(随机2),a3(随机3)而不是显示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

1 个答案:

答案 0 :(得分:1)

一个选项可能是使用grid命令深入挖掘图例的结构,并用a1,a2,a3替换boxplot键。

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)