您的位置:首页 > 其它

R语言ggplot2之图例的设置

2015-09-19 22:35 573 查看

引言

图例的设置包括移除图例、改变图例的位置、改变标签的顺序、改变图例的标题等。

移除图例

有时候你想移除图例,使用 guides()

library(ggplot2)
p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
p + guides(fill=FALSE)




改变图例的位置

我们可以用theme(legend.position=…)将图例移到图表的上方、下方、左边和右边。

p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
scale_fill_brewer(palette="Pastel2")
#上方
p + theme(legend.position="top")#左边left,右边 right, 底部bottom




改变图例标签的顺序

我们可以设置图例的指定顺序,也可以逆转图例的位置。

p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
#使用limit参数设置图例位置
p + scale_fill_discrete(limits=c("trt1", "trt2", "ctrl"))
#使用guides(fill=guide_legend(reverse=TRUE))逆转图例
p + guides(fill=guide_legend(reverse=TRUE))






设置图例的标题

我们可以改变图例的标题,也可以改变标题的主题格式,还可以删除图例标题。

#改变标题名字 用labs()
p + labs(fill="Condition")
# 设置图例的标题的字体、颜色、大小用theme(legend.title=element_text())
p + theme(legend.title=element_text(face="italic", family="Times", colour="red",
size=14))
#移除图例标题
#增加 guides(fill=guide_legend(title=NULL))函数即可移除图例标题
ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
guides(fill=guide_legend(title=NULL))








设置图例的标签

library(gcookbook)
#改变标签的名字
p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
p + scale_fill_discrete(labels=c("Control", "Treatment 1", "Treatment 2"))
#改变标签的主题
p + theme(legend.text=element_text(face="italic", family="Times", colour="red",
size=14))
#多行图例标签的展示
#有时候标签名字较长,一行展示不够美观,需要多行呈现 加一个\n
p + scale_fill_discrete(labels=c("Control", "Type 1\ntreatment",
"Type 2\ntreatment"))






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: