ggplot2--Legend(图例操作)

本文介绍如何使用ggplot2包定制图例样式,包括背景、键值、文本、位置等属性调整方法,并演示了如何改变图例标签及标题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Base Plot

xy <- data.frame(x=1:10, y=10:1, type = rep(LETTERS[1:2], each=5))
p=ggplot(data=xy)+geom_point(aes(x=x,y=y,color=type))
p
[转载]ggplot2--Legend(图例操作)

legend.background (rect)

# color does not work, use colour instead
p+opts(legend.background=theme_rect(colour="purple",fill="pink",size=3,linetype="dashed"))
[转载]ggplot2--Legend(图例操作)

legend.key (rect)

p+opts(legend.key=theme_rect(colour='purple',fill='pink',size=0.5,linetype='dashed'))
[转载]ggplot2--Legend(图例操作)

legend.key.size (unit)

# to use unit, you need to load package grid, i.e. library(grid)
p+opts(legend.key.size=unit(2,'cm'))
[转载]ggplot2--Legend(图例操作)

legend.key.width (unit)

p+opts(legend.key.width=unit(5,'cm'))
[转载]ggplot2--Legend(图例操作)

legend.text (text)

p+opts(legend.text = theme_text(colour = 'red', angle = 45, size = 10, hjust = 3, vjust = 3, face = 'bold'))
[转载]ggplot2--Legend(图例操作)

change legend labels

# breaks=c('A','B'), 'A' and 'B' are the default legend in xy
p+scale_colour_hue(name="my legend", breaks=c('A','B'), labels=c('AAA','BBB'))
[转载]ggplot2--Legend(图例操作)

legend.title (text)

p+opts(legend.title = theme_text(colour = 'red', angle = 45, size = 10, hjust = 3, vjust = 7, face = 'italic'))
[转载]ggplot2--Legend(图例操作)

legend.position (?)

# get rid of legend
p+opts(legend.position='none')
# move legend to the left
p+opts(legend.position='left')
define relative coordinates on plot c(x, y) between 0 and 1
p+opts(legend.position=c(0.5,0.5))
[转载]ggplot2--Legend(图例操作) [转载]ggplot2--Legend(图例操作) [转载]ggplot2--Legend(图例操作)

legend.justification (?)

Justification defines which side of the legend that the legend.position coordinates refer to
  p+ opts(legend.justification = 'right', legend.position=c(0.25,0.3))
can use left, right, centre or numeric value (0 ≤ x ≤ 1)
[转载]ggplot2--Legend(图例操作)


Reference
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值