观,可以使读图者更快速、更准确的了解图形表达的含义。
ggplot2包中的annotate()函数帮助用户给图形的指定位置添加注释,一般注释可以从点、线和面的角度进行修饰,对应的geom参数是text、segment、pointrange、rect。
基本图形示例:
library(ggplot2) x<-c(2015,2016,2017,2018,2019,2020) y<-c(12,13,14,25,36,57) test<-data.frame(Year=x,Num=y) p0 <- ggplot(data = test, mapping = aes(x = Year, y = Num)) + geom_line(colour = 'blue', size = 1) + geom_point(colour = 'red', size = 2)
p0
一 图形主体信息注释
labs()函数或ggtitle()函数为图形添加标题 p1 <- p0 + labs(title="小白学R",subtitle = "学不会",caption = "坚持") p1 annotate()函数添加信息 p2 <- p1 + #矩阵(rect),框出重点关注区域 annotate(geom = 'rect', xmin = 2018, ymin = 25, xmax = 2019, ymax = 40, alpha = 0.4) + #带箭头的射线(segment) annotate('segment', x = 2019, y = 20, xend = 2018.5, yend = 25, size = 1.2, arrow = arrow()) +
#文本型注释
annotate('text', x = 2019, y = 20, label = '输入信息1', colour = 'red')+ #参考线 geom_abline()、geom_vline() geom_hline(yintercept = mean(test$Num), linetype = 2, col = 'red', size = 1) + annotate('text', x = 2016, y = mean(test$Num) + 3, label = paste('平均值:',round(mean(test$Num),2)))+ # 添加公式 ?plotmath查看数学表达式;parse设为TRUE annotate('text', x = 2017, y = 50, label = 'f(x) == frac(x+y,sqrt(2*pi,3))*e^-log(2,x)', parse = TRUE, size = 3, colour = 'red')
p2
二 图形坐标轴信息修改
坐标轴显示范围
p3 <- p2 + scale_x_continuous(limits = c(2014,2022)) ;p3 ## 一般使用倍数来限定大小,最小值有个0 p3 <- p1 + xlim(min(test$Num, 0)*1.2, max(test$Num)*1.2)
坐标轴刻度、标签
# X 轴每隔 2 个单位显示一个刻度 ; 改变刻度文字,label要与刻度一样多 p2 + scale_x_continuous(breaks=seq(2015, 2020, 2) , labels = c("A","B","C"))
横坐标轴相关设置
##只去掉 X 轴的刻度标签 p4 <- p2 + theme(axis.ticks.x = element_blank()) + scale_x_continuous(breaks=test$Year, labels = paste(test$Year,'Year')) + theme(axis.text.x = element_text(size = 10,color = "skyblue" ,vjust = 0.5, hjust = 0.5, angle = 45))+ ## 删去网格线 theme(panel.grid =element_blank()) + ## 删去外层边框 theme(panel.border = element_blank()) + ## 再加上坐标轴(无刻度、无标签) theme(axis.line = element_line(size=1, colour = "black"))
/
p4
##详见ggplot2-theme
三、旋转坐标轴
只需添加coord_flip()函数就可以实现
p5 <- p4 + coord_flip();p5
基本图形的注释及坐标信息的更改,待补充 。。。