修改一組legend寥裂,導(dǎo)入iris數(shù)據(jù)集盔沫,默認畫圖:
data(iris)
p <- ggplot(iris, aes(x = Species, y = Sepal.Width, fill = Species)) + geom_boxplot(outlier.colour = NA) + theme_bw()
p
- 修改legend的題目 (title)
p + labs(fill = "Type")
# 或者
p + p + guides(fill = guide_legend(title = 'Type'))
- 修改legend的位置 (position)
修改位置有兩種方式,一種是直接給出四種位置中的一個:“l(fā)eft”,“top”, “right”, “bottom”, “none”焕数。
p + theme(legend.position="top")
另一種是給出數(shù)值型位置坐標(biāo):
p + theme(legend.position = c(0.7, 0.1),
legend.direction = "horizontal")
- 反轉(zhuǎn) (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)))
- 去掉legend
p + theme(legend.position = "none")
# 或者
p + guides(fill=FALSE)
- 修改legend字體大小辆它、顏色
p + theme(legend.title = element_text(color = "blue", size = 15),
legend.text = element_text(color = "orange", size = 12))
- 修改背景 (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")
)
- 添加legend的外邊框
p + theme(
legend.background = element_rect(color = "blue", linetype = "solid", size = 1)
)
- 修改標(biāo)簽 (labels) 和順序 (order)
# 修改的是box的順序
p + scale_x_discrete(limits=c("versicolor", "virginica", "setosa"))
# 修改標(biāo)簽名字
p + scale_fill_discrete(name = "Species", labels = c("S", "V1", "V2"))
- 修改顏色
p + scale_fill_manual(values = c("#d8b365", "#f5f5f5", "#5ab4ac"))
修改多組的legend获茬,導(dǎo)入mtcars數(shù)據(jù)集并畫圖:
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
- 修改位置
p + theme(legend.position = "bottom",
legend.box = "vertical")
- 修改順序
p + guides(size = guide_legend(order = 1),
color = guide_legend(order = 2),
shape = guide_legend(order = 3))
- 去掉其中的兩個legend
p + guides(shape = FALSE, size = FALSE)
歡迎關(guān)注~