ggplot绘制常见的统计图

最后发布时间:2020-05-28 23:34:13 浏览量:

https://www.cnblogs.com/songbiao/p/12490831.html

install.packages('ggplot2', repos = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/")

图片alt

图片alt

R基础绘图

library(ggplot2)
year <- c(2017,2018,2022,2024)
money <- c(1018,1246,1780,2000)
plot(year,money,type="b",col="red")

图片alt

qplot 绘图

df <- data.frame(Year = year,Money = money)
qplot(year,Money,data=df)

图片alt

使用空气质量数据

qplot(Wind,Temp,data=airquality,color=Month)

图片alt

将月份转换为分类变量

airquality$Month <- factor(airquality$Month)
qplot(Wind,Temp,data=airquality,color=Month)

图片alt

固定颜色

qplot(Wind,Temp,data=airquality,color=I("red"))

图片alt

形状分类

qplot(Wind,Temp,data=airquality,shape=Month)

大小分类

qplot(Wind,Temp,data=airquality,size=Month)

添加图注

qplot(Wind,Temp,data=airquality,color=Month,xlab="Winds",
      ylab="Temps",main = "Wind~Temp")

添加统计信息

qplot(Wind,Temp,data=airquality,color=Month,xlab="Winds",
      ylab="Temps",main = "Wind~Temp",geom = c("point","smooth"))

图片alt

划分多面板

qplot(Wind,Temp,data=airquality,color=Month,xlab="Winds",
      ylab="Temps",main = "Wind~Temp",geom = c("point","smooth"),
      facets = .~Month)

图片alt

ggplot 绘图

ggplot(airquality,aes(Wind,Temp))+
  geom_point(aes(color=factor(Month)),
              alpha=0.4,size=5)

图片alt

添加统计信息

ggplot(airquality,aes(Wind,Temp))+
  geom_point()+
  geom_smooth()

线性回归

ggplot(airquality,aes(Wind,Temp))+
  geom_smooth(method = "lm",se=FALSE)

根据每一个月份回归

ggplot(airquality,aes(Wind,Temp))+
  geom_smooth(method = "lm",se=FALSE,aes(color=Month))

ggplot(airquality,aes(Wind,Temp,col=factor(Month)))+
  geom_smooth(method = "lm",se=FALSE)

基于整体数据进行拟合

ggplot(airquality,aes(Wind,Temp,col=factor(Month) ,group=1))+
  geom_point()+
  geom_smooth(method = "lm",se=FALSE)

ggplot(airquality,aes(Wind,Temp,col=factor(Month)))+
  geom_point()+
  geom_smooth(method = "lm",se=FALSE,aes(group=1))+
  geom_smooth(method = "lm",se=FALSE)

图片alt

图片alt

颜色的使用

library(RColorBrewer)
myColors <- c(brewer.pal(5,"Dark2"),"black")
display.brewer.pal(5,"Dark2")

ggplot(airquality,aes(Wind,Temp,col=factor(Month)))+
  geom_point()+
  geom_smooth(method = "lm",se=FALSE,aes(group=1,col="All"))+
  geom_smooth(method = "lm",se=FALSE)+
  scale_color_manual("Month",values = myColors)

主题的使用

ggplot(airquality,aes(Wind,Temp,col=factor(Month)))+
  geom_point()+
  geom_smooth(method = "lm",se=FALSE)+
  scale_color_manual("Month",values = myColors)+
  facet_grid(.~Month)+
  theme_classic()

案例

曲线图

数据

图片alt

绘图

ggplot(data = mydata, aes(x = year, y = produce))+
  scale_x_continuous(breaks=seq(2009,2016,1))+
  scale_y_continuous(breaks=seq(300,450,10))+
  geom_line()+
  geom_point()+
  guides(fill = FALSE) + xlab("年份") +
  ylab("产量:万吨") + ggtitle("2009~2016年中国药材市场走势图")+theme_bw()+
  geom_text(aes(label=produce, y=produce+9,x=year-0.2), 
            position=position_dodge(0.9), 
            vjust=0) +
  theme(plot.title = element_text(hjust = 0.5))

图片alt