本文更新地址:http://blog.csdn.net/tanzuozhev/article/details/51108040
本文在 Scatterplots (ggplot2) 的基础上加入了自己的理解
图例用来解释图中的各种含义,比如颜色,形状,大小等等, 在ggplot2中aes
中的参数(x, y 除外)基本都会生成图例来解释图形, 比如 fill, colour, linetype, shape.
基本箱线图(带有图例)
library(ggplot2)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
bp
移除图例
Use guides(fill=FALSE), replacing fill with the desired aesthetic. 使用 guides(fill=FALSE)
移除由ase
中 匹配的fill
生成的图例, 也可以使用theme
You can also remove all the legends in a graph, using theme.
bp + guides(fill=FALSE)
# 也可以这也
bp + scale_fill_discrete(guide=FALSE)
# 移除所有图例
bp + theme(legend.position="none")
修改图例的内容
改变图例的顺序为 trt1, ctrl, trt2:
bp + scale_fill_discrete(breaks=c("trt1","ctrl","trt2"))
根据不同的分类,可以使用
scale_fill_manual
, scale_colour_hue
,scale_colour_manual
, scale_shape_discrete
, scale_linetype_discrete
等等.
颠倒图例的顺序
# 多种方法
bp + guides(fill = guide_legend(reverse=TRUE))
# 也可以
bp + scale_fill_discrete(guide = guide_legend(reverse=TRUE))
# 还可以这也
bp + scale_fill_discrete(breaks = rev(levels(PlantGrowth$group)))
隐藏图例标题
# Remove title for fill legend
bp + guides(fill=guide_legend(title=NULL))