9  annotate()

9.1 annotate

library(ggplot2)
ggplot(mpg,aes(displ, hwy , color = cyl)) + geom_point()

ggplot(mpg,aes(displ, hwy , color = cyl)) + 
  geom_point()+
  annotate("rect",xmin=4.5,xmax=7.1,ymin=0,ymax=27,color="red",alpha=0.3,size=2)

ggplot(mpg,aes(displ, hwy , color = cyl)) + 
  geom_point()+
  annotate("segment",x=2.5,y=20,xend=3,yend=35,color="blue",size=10,alpha=0.1)

ggplot(mpg,aes(displ, hwy , color = cyl)) + 
  geom_point()+
  annotate("segment",x=2.5,y=20,xend=3,yend=35,color="blue",
           arrow=arrow(end="last",angle=30,length=unit(1,"cm")))

9.2 geom_text

ggplot(mpg,aes(displ, hwy , color = cyl)) + geom_point()

ggplot(mpg,aes(displ, hwy , color = cyl)) + 
  geom_point()+
  geom_text(label="TEST",color="red")

ggplot(mpg,aes(displ, hwy , color = cyl)) + 
  geom_point()+
  geom_text(aes(label=manufacturer),color="red")

ggplot(mpg,aes(displ, hwy , color = cyl)) + 
  geom_point()+
  geom_text(x=4,y=40,label="TEST",color="red",alpha=0.1)

ggplot(mpg,aes(displ, hwy , color = cyl)) + 
  geom_point()+
  geom_text(label="TEST",color="red",vjust=0.3,hjust=-0.2)

9.3 实例

── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.4.1 
✔ readr   2.1.3      ✔ forcats 0.5.2 
✔ purrr   0.3.5      
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::arrange()   masks plyr::arrange()
✖ purrr::compact()   masks plyr::compact()
✖ dplyr::count()     masks plyr::count()
✖ dplyr::failwith()  masks plyr::failwith()
✖ dplyr::filter()    masks stats::filter()
✖ dplyr::id()        masks plyr::id()
✖ dplyr::lag()       masks stats::lag()
✖ dplyr::mutate()    masks plyr::mutate()
✖ dplyr::rename()    masks plyr::rename()
✖ dplyr::summarise() masks plyr::summarise()
✖ dplyr::summarize() masks plyr::summarize()
lm_labels <- function(dat) {
    mod <- lm(hwy ~ displ, data=dat)
    formula <- sprintf("italic(y) == %.2f %+.2f * italic(x) ",  round(coef(mod)[1], 2), round(coef(mod)[2], 2))
    r <- cor(dat$displ, dat$hwy)
    r2 <- sprintf("italic(R^2) == %.2f", r^2)
    data.frame(formula=formula, r2=r2, stringsAsFactors=FALSE)}

labels<-ddply(mpg,"cyl",lm_labels);labels[2,]<-c("5","数据个数太少","无法拟合")
Warning in cor(dat$displ, dat$hwy): the standard deviation is zero
labels
  cyl                               formula                  r2
1   4 italic(y) == 46.60 -8.29 * italic(x)  italic(R^2) == 0.34
2   5                          数据个数太少            无法拟合
3   6 italic(y) == 36.38 -3.98 * italic(x)  italic(R^2) == 0.26
4   8 italic(y) == 10.97 +1.30 * italic(x)  italic(R^2) == 0.05
ggplot(mpg,aes(displ,hwy))+ 
  geom_point()+
  facet_grid(cyl~.)+
  geom_smooth(se=FALSE,method="lm")+
  geom_text(x=5,y=40,aes(label=formula),data=labels,parse=TRUE,vjust=0)+
  geom_text(x=5,y=35,aes(label=r2),data=labels,parse=TRUE,vjust=-0.1)
`geom_smooth()` using formula 'y ~ x'