本文首发于微信公众号“生信补给站”,https://mp.weixin.qq.com/s/A5nqo6qnlt_5kF3_GIrjIA微信
mtcars数据集做为示例数据markdown
library(ggplot2)#查看数据集 head(mtcars) # 将cyl gear变量转为因子变量 mtcars$cyl<-as.factor(mtcars$cyl) mtcars$gear <- as.factor(mtcars$gear)
#gear为横坐标,对mpg作箱线图,gear填充颜色 p <- ggplot(mtcars, aes(x=gear, y=mpg, fill=gear)) + geom_boxplot() p
使用 theme() 参数设置legend位置app
# 可选参数为“left”,“top”, “right”, “bottom”. p + theme(legend.position="bottom")
# 数值向量 c(x,y) 调控位置 p + theme(legend.position = c(0.8, 0.2))
# legend title p + theme(legend.title = element_text(colour="blue", size=10, face="bold")) # legend labels p + theme(legend.text = element_text(colour="blue", size=10, face="bold"))
#fill设置legend box背景色,colour设置边框颜色 p + theme(legend.background = element_rect(fill="lightblue", size=0.5, linetype="solid", colour ="darkblue"))
scale_x_discrete自定义设置顺序ide
p + scale_x_discrete(limits=c("3", "5", "4"))
# 去除legend title p + theme(legend.title = element_blank()) # 去除整个legend p + theme(legend.position='none')
使用guides()参数来设置或移除特定的美学映射(fill, color, size, shape等).
因子变量cyl和gear映射为点图的颜色和形状,qsec决定点的大小。函数
p <- ggplot(data = mtcars, aes(x=mpg, y=wt, color=cyl, size=qsec, shape=gear))+ geom_point()
# 不设定specific aesthetic时候
p
# 更改 legend position p +theme(legend.position="bottom") # Horizontal legend box p +theme(legend.position="bottom", legend.box = "")
使用 guide_legend() 参数:学习
p+guides(color = guide_legend(order=1), size = guide_legend(order=2), shape = guide_legend(order=3))
经过设置FALSE,可不展现对应的legendui
p+guides(color = FALSE)
也能够使用scale_xx.函数去掉特定的legendspa
# Remove legend for the point shape p+scale_shape(guide=FALSE) # Remove legend for size p +scale_size(guide=FALSE) # Remove legend for color p + scale_color_manual(values=c('#999999','#E69F00','#56B4E9'), guide=FALSE)
经过以上参数的设置即完成对所绘制图形的legend的细节修改,获得本身所须要的图形。3d