1. 散点图
library(ggplot2)
library(tidyverse)
library(cowplot)
#准备数据
set.seed(1000)
small_diamonds<-sample_n(diamonds,size=500)
dim(small_diamonds)
colnames(small_diamonds)
[1] "carat" "cut" "color" "clarity" "depth" "table" "price" "x" "y" "z"
ggplot(data=small_diamonds,aes(x=carat,y=price))+
geom_point(shape=21,size=4,aes(fill= cut))+geom_smooth()
#绘图,加拟合曲线,其中method=lm 加拟合直线,不加method的画默认是拟合曲线
p1<-ggplot(data=small_diamonds,aes(x=carat,y=price))+
geom_point(shape=21,size=4,aes(fill= cut))+geom_smooth(method = "lm")
#去掉拟合曲线的置信区间 se=F
p2<-ggplot(data=small_diamonds,aes(x=carat,y=price))+
geom_point(shape=21,size=4,aes(fill= cut))+geom_smooth(method = "lm",se=F)
#不同分组都画拟合曲线 aes(group=cut,color=cut),
p3<-ggplot(data=small_diamonds,aes(x=carat,y=price))+
geom_point(shape=21,size=4,aes(fill= cut))+geom_smooth(aes(group=cut,color=cut),method = "lm",se=F)
plot_grid(p1,p2,p3)

image.png
计算相关性
> cor.test(small_diamonds$carat,small_diamonds$price,method = "pearson")
Pearson's product-moment correlation
data: small_diamonds$carat and small_diamonds$price
t = 59.696, df = 498, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
0.9249769 0.9466265
sample estimates:
cor
0.9366908
添加注释 annotate('text',x=2.5,y=20,label="r = 0.91; pvalue = 2.2e-16")
ggplot(data=small_diamonds,aes(x=carat,y=price))+theme_bw()+
geom_point(shape=21,size=4,aes(fill= cut))+geom_smooth(method = "lm",se=F)+
annotate('text',x=2.5,y=20,label="r = 0.91; pvalue = 2.2e-16")+
theme(legend.position = c(0.1,0.83))

image.png
添加边际图
1. 安装ggextra
install.packages("ggextra")
library(ggextra)
p3 <- ggplot(data=small_diamonds,aes(x=carat,y=price))+theme_bw()+
geom_point(shape=21,size=4,aes(fill= cut))+geom_smooth(aes(group=cut,color=cut),method = "lm",se=F)+
annotate('text',x=2.5,y=20,label="r = 0.91; pvalue = 2.2e-16")+
theme(legend.position = c(0.1,0.83))
ggExtra::ggMarginal(
p = p3,
type = 'density',
margins = 'both',
size = 5,
colour = 'black',
fill = 'gray'
2. 选择代码块
, 然后选择add in里面的 ggExtra插件

image.png

image.png
3. 添加边际图

image.png
添加地毯线
ggplot(data=small_diamonds,aes(x=carat,y=price))+theme_bw()+
geom_point(shape=21,size=4,aes(fill= cut))+geom_smooth(aes(group=cut,color=cut),method = "lm",se=F)+
annotate('text',x=2.5,y=20,label="r = 0.91; pvalue = 2.2e-16")+
theme(legend.position = c(0.1,0.83))+
geom_rug(aes(color=cut),length = unit(3,"mm"))

image.png
网友评论