打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
R语言ggplot2之图例的设置

引言

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

移除图例

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

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

改变图例的位置

我们可以用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
  • 1
  • 2
  • 3
  • 4

改变图例标签的顺序

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

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))
  • 1
  • 2
  • 3
  • 4
  • 5


设置图例的标题

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

#改变标题名字 用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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9



设置图例的标签

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))#多行图例标签的展示#有时候标签名字较长,一行展示不够美观,需要多行呈现 加一个\np + scale_fill_discrete(labels=c("Control", "Type 1\ntreatment","Type 2\ntreatment"))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Legends
ggplot2-设置图例(legend)
R语言数据可视化教程(ggplot2)控制图形的整体外观及增加图例
ggplot_legend
ggplot2|从0开始绘制箱线图
R使用笔记: ggplot2
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服