如何在ggplot2 geom_boxplot中使用实心方块作为图例键

时间:2013-08-01 15:44:14

标签: r ggplot2 legend boxplot

我正在尝试使用R ggplot2 包制作一个箱形图。

但是我只能得到这样的传奇。无论如何我可以将这些图例键改为实心方块,而不是使用那些带中心线的小盒子吗?

我使用的代码是:

print(ggplot(mydata,aes(x=factor(sp),fill=factor(CommunityType),y=Abundance*100))+geom_boxplot(show_guide=FALSE)
      +theme(axis.text = element_text(colour = "black",size=10))
      +scale_y_continuous(" RA (%) ")+scale_x_discrete(limits=taxalist[1:5]," ")
      +scale_fill_manual(name = "MY type", values = mycol[1:nmc])
      +theme_bw() + guides(fill=guide_legend(title=NULL))+theme(legend.position=c(1,1),legend.justification=c(1,1)) 
      +theme(legend.key = element_blank(),legend.key.size = unit(1.5, "lines"))
      +theme( panel.grid.major = element_blank(),  panel.grid.minor = element_blank(),  panel.background = element_blank())  )

抱歉,我无法在此处描述我的问题。

1 个答案:

答案 0 :(得分:4)

这里的图例显示为简单的正方形,使用了我见过Winston Change使用here的黑客变种。 (我正在使用钻石数据集。)

enter image description here

我的想法是绘制geom_points(你可以控制它的图例,并完全抑制boxplot的图例)

library(ggplot2)
p <- ggplot() + geom_point(data=diamonds, aes(x=cut, y=mean(depth), color=clarity), shape=15, size=5)
p <- p + guides(color=guide_legend(title=NULL)) 
p <- p + theme(legend.key = element_blank())
p <- p  + geom_boxplot(data=diamonds,aes(x=cut,fill=factor(clarity),y=depth)) + guides(fill=FALSE)
p

另请查看Hadley的Legend-Attributes page on github