R IN ACTION SELF-TUTORIAL-74 在绘制

2021-12-23  本文已影响0人  RashidinAbdu
  1. 根据数据进行绘图:

#安装一些相关的包:
#install.packages("ggpmisc")
#install.packages("ggpubr")
library(ggplot2)
library(ggsave)

df=diamonds[sample(1:dim(diamonds)[1],40),]
df$price=df$price / 10000
p=df%>%ggplot(aes(carat,price))+
  geom_point(size=4,alpha=0.3,color="#6baed6")+
  geom_smooth(method = "lm", formula = y~x, color = "#756bb1", fill = "#cbc9e2")+ #颜色选自https://colorbrewer2.org/
  theme_bw()+
  theme(
    panel.grid.major = element_blank(),panel.grid.minor = element_blank()
  )
p
image.png
library(ggpubr)
p+stat_cor()
image.png
library(ggpmisc)
p+stat_poly_eq(aes(label=paste(..eq.label..,..adj.rr.label..,..p.value.label..,sep = "~~~~")),formula = y~x,parse=T,size=2.5)
image.png

这一行paste()中的内容是一个类似Latex的表达,“~”表示空格,parse=T表示将这个语句翻译成可读形式;size=2.5表示字体大小

cor=round(cor(df$carat,df$price),2)
p+stat_poly_eq(aes(label=paste("italic(r)~`=`~",cor,sep = "")),formula = y~x,parse=T,size=4)
image.png
* 添加对应值的位置的调整:
p+stat_poly_eq(aes(label=..eq.label..),formula = y~x,
               parse=T,size=4)+
  stat_cor(label.y=2.9,size=4)
image.png
p+stat_poly_eq(aes(label=..eq.label..),formula = y~x,
               parse=T,size=4)+
  stat_cor(label.y=1.5,size=4)
image.png

x=0.1212
y= round(x, digits = 2) 
y
image.png
上一篇 下一篇

猜你喜欢

热点阅读