Cook RR语言与统计分析数据-R语言-图表-决策-Linux-Python

ggplot2画图:legend整理(title/positio

2020-01-05  本文已影响0人  生信编程日常

修改一组legend,导入iris数据集,默认画图:

data(iris)
p <- ggplot(iris, aes(x = Species, y = Sepal.Width, fill = Species)) + geom_boxplot(outlier.colour = NA) + theme_bw()
p 
image.png
  1. 修改legend的题目 (title)
p + labs(fill = "Type")
# 或者
p + p + guides(fill = guide_legend(title = 'Type'))
image.png
  1. 修改legend的位置 (position)

修改位置有两种方式,一种是直接给出四种位置中的一个:“left”,“top”, “right”, “bottom”, “none”。

p + theme(legend.position="top")
image.png

另一种是给出数值型位置坐标:

p + theme(legend.position = c(0.7, 0.1),
          legend.direction = "horizontal")
image.png
  1. 反转 (reverse) legend的顺序 (order)
p + guides(fill = guide_legend(reverse=TRUE))
# 或者
p + scale_fill_discrete(guide = guide_legend(reverse=TRUE))
# 或者
p + scale_fill_discrete(breaks = rev(levels(iris$Species)))
image.png
  1. 去掉legend
p + theme(legend.position = "none")
# 或者
p + guides(fill=FALSE)
image.png
  1. 修改legend字体大小、颜色
p + theme(legend.title = element_text(color = "blue", size = 15),
          legend.text = element_text(color = "orange", size = 12))
image.png
  1. 修改背景 (background) 颜色、key的大小和宽度
p + theme(
  # Change legend background color
  legend.background = element_rect(fill = "gray"),
  legend.key = element_rect(fill = "yellow", color = NA),
  # Change legend key size and key width
  legend.key.size = unit(1.5, "cm"),
  legend.key.width = unit(1,"cm") 
  )
image.png
  1. 添加legend的外边框
p + theme(
  legend.background = element_rect(color = "blue", linetype = "solid", size = 1)
  )
image.png
  1. 修改标签 (labels) 和顺序 (order)
# 修改的是box的顺序
p + scale_x_discrete(limits=c("versicolor", "virginica", "setosa"))
image.png
# 修改标签名字
p + scale_fill_discrete(name = "Species", labels = c("S", "V1", "V2"))
image.png
  1. 修改颜色
p + scale_fill_manual(values = c("#d8b365", "#f5f5f5", "#5ab4ac"))
image.png

修改多组的legend,导入mtcars数据集并画图:

data(mtcars)
mtcars$cyl<-as.factor(mtcars$cyl)
mtcars$gear <- as.factor(mtcars$gear)
p <- ggplot(data = mtcars, aes(x = mpg, y = wt))+
    geom_point(aes(color = cyl, size = qsec, shape = gear)) + theme_bw()
p
image.png
  1. 修改位置
p + theme(legend.position = "bottom",
          legend.box = "vertical")
image.png
  1. 修改顺序
p + guides(size = guide_legend(order = 1),
         color = guide_legend(order = 2),
         shape = guide_legend(order = 3))
image.png
  1. 去掉其中的两个legend
p + guides(shape = FALSE, size = FALSE)
image.png

欢迎关注~


ggplot2画图:legend整理(title/position/order...)
上一篇下一篇

猜你喜欢

热点阅读