ggplot2入门大全(给图像加注解)

注解会在图像中添加元数据,元数据依然是数据,所以可以使用以下函数:
geom_text():可添加文本说明或者为点添加标签;
geom_rect():标注图形中你感兴趣的区域;
geom_line()、geom_path()、geom_segment():添加直线,可以在直线上绘制箭头;
geom_vline()、geom_hline()、geom_abline():在图形中添加参照线(基准线),其跨度为整张图像。
一般来说,注解既可添加在前景(必要时使用alpha函数以保证能看清数据)也可添加在背景中。添加于背景时,默认使用白色字体。
下面依然使用economics数据集举例说明:
添加注解标明各个总统的当政时间

library(ggplot2)
ggplot(economics,aes(date,unemploy))+geom_line()
presidential <- subset(presidential,start > economics$date[1])
ggplot(economics)+
  geom_rect(aes(xmin=start,xmax=end,fill=party),
  ymin=-Inf,ymax=Inf,alpha=0.2,data=presidential)+
  geom_vline(aes(xintercept=as.numeric(start)),
  data=presidential,colour="grey50",alpha=0.5)+
  geom_text(aes(x=start,y=2500,label=name),
  data=presidential,size=3,vjust=0,hjust=0,nudge_x=50)
  geom_line(aes(date,unemploy))+
  scale_fill_manual(values = c("blue","red"))

总统当政时间
图看起来还不错,但好像有些繁琐。

各类注解,尤其是参照线,在通过分面比较组间关系时格外有用,不过其实用的也不多。。

ggplot(diamonds,aes(log10(carat),log10(price)))+
  geom_bin2d()+facet_wrap(~cut,nrow = 1)

在这里插入图片描述

mod_coef <- coef(lm(log10(price)~log10(carat),
                    data=diamonds))
ggplot(diamonds,aes(log10(carat),log10(price)))+
  geom_bin2d()+geom_abline(intercept = mod_coef[1],
  slope=mod_coef[2],colour="white",size=1)+
  facet_wrap(~cut,nrow = 1)

在这里插入图片描述

预告:下一篇介绍群组几何对象
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值