天天看点

【R】ggplot2——绘图实例ggplot2——绘图实例

ggplot2——绘图实例

示例数据

> str(mpg)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':	234 obs. of  11 variables:
 $ manufacturer: chr  "audi" "audi" "audi" "audi" ...
 $ model       : chr  "a4" "a4" "a4" "a4" ...
 $ displ       : num  1.8 1.8 2 2 2.8 2.8 3.1 1.8 1.8 2 ...
 $ year        : int  1999 1999 2008 2008 1999 1999 2008 1999 1999 2008 ...
 $ cyl         : int  4 4 4 4 6 6 6 4 4 4 ...
 $ trans       : chr  "auto(l5)" "manual(m5)" "manual(m6)" "auto(av)" ...
 $ drv         : chr  "f" "f" "f" "f" ...
 $ cty         : int  18 21 20 21 16 18 18 18 16 20 ...
 $ hwy         : int  29 29 31 30 26 26 27 26 25 28 ...
 $ fl          : chr  "p" "p" "p" "p" ...
 $ class       : chr  "compact" "compact" "compact" "compact" ...
           

变量含义

  • manufacturer;生产商
  • model;型号
  • displ;engine displacement, in litres;发动机排量
  • year;生产年份
  • cyl.;number of cylinders;汽缸数
  • trans;type of transmission;传动装置变速器类型
  • drv;f = front-wheel drive, r = rear wheel drive, 4 = 4wd;前轮驱动、后轮驱动和四轮驱动
  • cty;city miles per gallon;每加仑英里数
  • hwy;highway miles per gallon;每加仑高速英里数
  • fl;
  • class;类型

图形属性

  • ggplot与plot的第一个大的差别在于对图中点设定颜色(或大小、形状,即图形属性)时采用不同的实现方式。
  • 在plot中,用户需要将数据中的一个分类变量(如“苹果”、“香蕉”、“桃子”)转换为plot可以理解的形式(如“red”“yellow”“green”)。
  • ggplot可以自动完成这个过程,并能够自动生成一张图例,用以展示数据取值与图形属性之间的对应关系,这使得向图中添加额外的信息非常简便。
  • 每一个图形属性都对应了一个称为标度的函数,其作用是将数据的取值映射到该图形属性的有效取值。

散点图

p <- ggplot(data=mpg,mapping = aes(x=cty,y=hwy))
p + geom_point()
           
【R】ggplot2——绘图实例ggplot2——绘图实例
> summary(p)
**data**: manufacturer, model, displ, year, cyl, trans, drv, cty,
  hwy, fl, class [234x11]
**mapping**:  x = ~cty, y = ~hwy
**faceting**: <ggproto object: Class FacetNull, Facet, gg>
    compute_layout: function
    draw_back: function
    draw_front: function
    draw_labels: function
    draw_panels: function
    finish_data: function
    init_scales: function
    map_data: function
    params: list
    setup_data: function
    setup_params: function
    shrink: TRUE
    train_scales: function
    vars: function
    super:  <ggproto object: Class FacetNull, Facet, gg>
           
> summary(p+geom_point())
data: manufacturer, model, displ, year, cyl, trans, drv, cty,
  hwy, fl, class [234x11]
mapping:  x = ~cty, y = ~hwy
faceting: <ggproto object: Class FacetNull, Facet, gg>
    compute_layout: function
    draw_back: function
    draw_front: function
    draw_labels: function
    draw_panels: function
    finish_data: function
    init_scales: function
    map_data: function
    params: list
    setup_data: function
    setup_params: function
    shrink: TRUE
    train_scales: function
    vars: function
    super:  <ggproto object: Class FacetNull, Facet, gg>
-----------------------------------
**geom_point**: na.rm = FALSE
**stat_identity**: na.rm = FALSE
**position_identity**:(width = NULL, height = NULL)
           

映射 mapping

将年份映射到颜色属性

p <- ggplot(mpg,aes(x=cty, y=hwy, colour=factor(year)))
p + geom_point()
           
【R】ggplot2——绘图实例ggplot2——绘图实例

统计变换 statistics

增加平滑曲线

p + geom_point() + stat_smooth()
           

两条光滑曲线

【R】ggplot2——绘图实例ggplot2——绘图实例

叠加图层

p <- ggplot(mpg, aes(x=cty,y=hwy))
p + geom_point(aes(colour=factor(year)))+stat_smooth()   
           

一条光滑曲线

【R】ggplot2——绘图实例ggplot2——绘图实例

与之等价的绘图方式:

d <- ggplot() +geom_point(data=mpg, aes(x=cty, y=hwy, colour=factor(year)))+stat_smooth(data=mpg, aes(x=cty, y=hwy))
print(d)
           

此时除了底层画布外,有两个图层,分别定义了geom和 stat。

> summary(d)
data: [x]
faceting: <ggproto object: Class FacetNull, Facet, gg>
    compute_layout: function
    draw_back: function
    draw_front: function
    draw_labels: function
    draw_panels: function
    finish_data: function
    init_scales: function
    map_data: function
    params: list
    setup_data: function
    setup_params: function
    shrink: TRUE
    train_scales: function
    vars: function
    super:  <ggproto object: Class FacetNull, Facet, gg>
-----------------------------------
mapping: x = ~cty, y = ~hwy, colour = ~factor(year) 
**geom_point**: na.rm = FALSE
stat_identity: na.rm = FALSE
position_identity 
mapping: x = ~cty, y = ~hwy 
**geom_smooth**: se = TRUE, na.rm = FALSE
stat_smooth: method = auto, formula = y ~ x, se = TRUE, n = 80, fullrange = FALSE, level = 0.95, na.rm = FALSE, method.args = list(), span = 0.75
position_identity 
           

用标度来修改颜色取值

p + geom_point(aes(colour=factor(year)))+
stat_smooth()+scale_color_manual(values =c('blue','red'))
           
【R】ggplot2——绘图实例ggplot2——绘图实例

将排量映射到散点大小

p +geom_point(aes(colour=factor(year),size=displ))+
stat_smooth()+scale_color_manual(values=c('blue2','red4'))
           
【R】ggplot2——绘图实例ggplot2——绘图实例
p + geom_point(aes(colour=factor(year),size=displ),alpha=0.5,position = "jitter") + 
stat_smooth()+scale_color_manual(values =c('blue2','red4'))+
scale_size_continuous(range = c(4, 10))
           
【R】ggplot2——绘图实例ggplot2——绘图实例

用坐标控制图形显示的范围

p + geom_point(aes(colour=factor(year),size=displ),alpha=0.5,position = "jitter")+ 
  stat_smooth()+
  scale_color_manual(values =c('blue2','red4'))+
  scale_size_continuous(range = c(4, 10))+
  coord_cartesian(xlim = c(15, 25),ylim=c(15,40))
           
【R】ggplot2——绘图实例ggplot2——绘图实例

利用facet分别显示不同年份的数据

p + geom_point(aes(colour=class, size=displ),alpha=0.5, position = "jitter")+ stat_smooth()+
  scale_size_continuous(range = c(4, 10))+
  facet_wrap(~ year, ncol=1)  #另一个分面函数facet_grid 
           
【R】ggplot2——绘图实例ggplot2——绘图实例

增加图名并精细修改图例

p <- ggplot(mpg,aes(x=cty,y=hwy))
p + geom_point(aes(colour=class,size=displ),alpha=0.5,position = "jitter")+stat_smooth()+
  scale_size_continuous(range = c(4, 10))+
  facet_wrap(~year,ncol=1)+options(title='汽车油耗与型号')+
  labs(y='每加仑高速公路行驶距离',x='每加仑城市公路行驶距离')+
  guides(size=guide_legend(title='排量'),colour = guide_legend(title='车型',override.aes=list(size=5)))
           
【R】ggplot2——绘图实例ggplot2——绘图实例

直方图

p<- ggplot(mpg,aes(x=hwy))
p + geom_histogram() #默认格式
           
【R】ggplot2——绘图实例ggplot2——绘图实例
> summary(p + geom_histogram())
data: manufacturer, model, displ, year, cyl, trans, drv, cty,
  hwy, fl, class [234x11]
mapping:  x = ~hwy
faceting: <ggproto object: Class FacetNull, Facet, gg>
    compute_layout: function
    draw_back: function
    draw_front: function
    draw_labels: function
    draw_panels: function
    finish_data: function
    init_scales: function
    map_data: function
    params: list
    setup_data: function
    setup_params: function
    shrink: TRUE
    train_scales: function
    vars: function
    super:  <ggproto object: Class FacetNull, Facet, gg>
-----------------------------------
geom_bar: na.rm = FALSE
**stat_bin**: binwidth = NULL, bins = NULL, na.rm = FALSE, pad = FALSE
position_stack 
           

直方图的几何对象中内置有默认的统计变换

p + geom_histogram(aes(fill=factor(year),y=..density..), alpha=0.3,colour='black')+
  stat_density(geom='line',position='identity',size=1.5, aes(colour=factor(year)))+
  facet_wrap(~year,ncol=1)
           
【R】ggplot2——绘图实例ggplot2——绘图实例

条形图

p <- ggplot(mpg, aes(x=class))
p + geom_bar()
           
【R】ggplot2——绘图实例ggplot2——绘图实例

根据计数排序后绘制的条形图

class2 <- mpg$class; class2 <- reorder(class2,class2,length)
mpg$class2 <- class2
p <- ggplot(mpg, aes(x=class2))
p + geom_bar(aes(fill=class2))
           
【R】ggplot2——绘图实例ggplot2——绘图实例
根据年份分别绘制条形图,position控制位置调整方式

position控制位置调整方式:

dodge:“避让”方式,即往旁边闪,如柱形图的并排方式就是这种。

fill:填充方式, 先把数据归一化,再填充到绘图区的顶部。

identity:原地不动,不调整位置

jitter:随机抖一抖,让本来重叠的露出点头来

stack:叠罗汉

p <- ggplot(mpg, aes(class2,fill=factor(year)))
p+geom_bar(position='identity',alpha=0.5)
           
【R】ggplot2——绘图实例ggplot2——绘图实例

并立方式

p+geom_bar(position='dodge')
           
【R】ggplot2——绘图实例ggplot2——绘图实例

叠加方式

p+geom_bar(position='stack')
           
【R】ggplot2——绘图实例ggplot2——绘图实例

相对比例

p+geom_bar(position='fill')
           
【R】ggplot2——绘图实例ggplot2——绘图实例

分面显示

p+geom_bar(aes(fill=class2))+facet_wrap(~year)
           
【R】ggplot2——绘图实例ggplot2——绘图实例

饼图

p <- ggplot(mpg, aes(x = factor(1), fill = factor(class))) +
  geom_bar(width = 1)
p + coord_polar(theta = "y")
           
【R】ggplot2——绘图实例ggplot2——绘图实例

箱线图

p <- ggplot(mpg, aes(class,hwy,fill=class))
p+geom_boxplot()
           
【R】ggplot2——绘图实例ggplot2——绘图实例
p+geom_violin(alpha=0.3,width=0.9)+geom_jitter(shape=21)  
#点,自动添加了扰动
           
【R】ggplot2——绘图实例ggplot2——绘图实例

总结

直方图
library(ggplot2)
data(packet='ggplot2')
head(diamonds)
p <- ggplot(diamonds,aes(x=carat))
p+geom_histogram()
p+geom_histogram(binwidth = 0.3)
p+geom_histogram(binwidth = 0.3,aes(fill=cut))
p+geom_histogram(binwidth = 0.3,aes(fill=cut),position = 'dodge')+xlim(0,3)
p+geom_histogram(binwidth = 0.3,aes(fill=cut),position = 'fill')+xlim(0,3)
p+geom_histogram(binwidth = 0.3,aes(fill=cut),position = 'stack')+xlim(0,3)
#position的三种类型为:dodge并列,stack堆叠,fill填充
p+geom_histogram(binwidth = 0.3,aes(fill=cut),position = 'dodge')+xlim(0,3)+coord_flip()
p+geom_histogram(binwidth = 0.3,aes(fill=cut),position = 'dodge')+xlim(0,3)+coord_flip()+facet_grid(.~cut)
p+geom_histogram(binwidth = 0.3,aes(fill=cut),position = 'dodge')+xlim(0,3)+ggtitle('直方图')+xlab('CARAT')+ylab('COUNT')
           
【R】ggplot2——绘图实例ggplot2——绘图实例
【R】ggplot2——绘图实例ggplot2——绘图实例
条形图
p <- ggplot(mpg,aes(x=manufacturer))
p+geom_bar(aes(fill=factor(year)),position = "dodge")
p+geom_bar(aes(fill=factor(year)),position = "dodge")+theme(axis.text.x = element_text(hjust = 1,angle = 45))
           
【R】ggplot2——绘图实例ggplot2——绘图实例
【R】ggplot2——绘图实例ggplot2——绘图实例
散点图
head(mpg)
p <- ggplot(mpg,aes(x=cty,y=hwy))
p+geom_point()
p+geom_point(colour='red')
p+geom_point(colour='red',size=5)
p+geom_point(colour='red',shape=4)
p+geom_point(colour='red',shape=4)+geom_smooth(method = 'lm')

r <- round(cor(mpg$cty,mpg$hwy),3)
p+geom_point(colour='red',shape=4)+geom_smooth(method = 'lm')+annotate("text",15,44,label=paste("Pearson's r:",r),size=3,colour="blue")

p <- ggplot(mpg,aes(x=cty,y=hwy,colour=factor(cyl)))+geom_point()
p+stat_smooth(method = 'lm')
ggplot(mpg,aes(x=cty,y=hwy))+geom_point(aes(colour=factor(cyl)))+stat_smooth(method = 'lm')

p <- ggplot(mpg,aes(x=cty,y=hwy,colour=factor(cyl)))+geom_point()
p+scale_color_manual(values = c("DarkGoldenrod4","Gold","#7FFFD4","#FF6A6A"))
ggplot(mpg,aes(x=cty,y=hwy))+geom_point(aes(colour=factor(cyl),size=year))+stat_smooth(method = 'lm')
ggplot(mpg,aes(x=cty,y=hwy))+geom_point(aes(colour=factor(cyl)))+stat_smooth(method = 'lm')+facet_grid(~year)
           
【R】ggplot2——绘图实例ggplot2——绘图实例
【R】ggplot2——绘图实例ggplot2——绘图实例
【R】ggplot2——绘图实例ggplot2——绘图实例

其他图形

玫瑰图
#随机生成100次风向,并汇集到16个区间内 
dir <- cut_interval(runif(100,0,360),n=16)
#随机生成100次风速,并划分成4种强度 
mag <- cut_interval(rgamma(100,15),4) 
sample <- data.frame(dir=dir,mag=mag)
#将风向映射到X轴,频数映射到Y轴,风速大小映射到填充色,生成条形图后再转为极坐标形式即可 
p <- ggplot(sample,aes(x=dir,y=..count..,fill=mag)) 
p + geom_bar()+ coord_polar()
           
【R】ggplot2——绘图实例ggplot2——绘图实例
面积图——连续变量的条形图
set.seed(3)  
#随机生成10维时序数据
t.step<-seq(0,20)  
#创建时间序列(0-20的time step)
grps<-letters[1:10] 
#创建十组变量名(从a到j)
grp.dat<-runif(length(t.step)*length(grps),5,15) 
#创建由随机数组成的十组变量的时序
grp.dat<-matrix(grp.dat,nrow=length(t.step),ncol=length(grps))  
#为绘图而创建所需的dataframe
grp.dat<-data.frame(grp.dat,row.names=t.step);grp.dat
p.dat<-data.frame(step=row.names(grp.dat),grp.dat,stringsAsFactors=F)
p.dat<-melt(p.dat,id='step')
p.dat$step<-as.numeric(p.dat$step)
library(ggplot2)
library(reshape2)
require(gridExtra) 
#导入ggplot2,绘制面积图
head(p.dat);p.dat
p<-ggplot(p.dat,aes(x=step,y=value),col=c('red','lightgreen','purple'))
p + geom_area(aes(fill=variable))+ theme(legend.position="bottom")  #不填满
p + geom_area(aes(fill=variable),position='fill')  

#可以展示成分数据,时间序列数据可以比较清楚的看到不同组成部分的比例。
p1<-p + geom_area(aes(fill=variable))+ theme(legend.position="bottom")  #不填满
p2<-p + geom_area(aes(fill=variable),position='fill') 
summary(p1)
print(p1)
summary(p2)
print(p2)
           
【R】ggplot2——绘图实例ggplot2——绘图实例
【R】ggplot2——绘图实例ggplot2——绘图实例
弦状图
chordDiagram(matp2,annotationTrack="grid",preAllocateTracks=list(track.height = 0.3))
##更改坐标轴
circos.trackPlotRegion(track.index=1, panel.fun=function(x,y) {
  xlim = get.cell.meta.data("xlim") 
  ylim = get.cell.meta.data("ylim")
  sector.name=get.cell.meta.data("sector.index")
  circos.text(mean(xlim), ylim[1], sector.name,facing="clockwise",
   niceFacing=TRUE,adj=c(0,0.5))},bg.border=NA)
           
【R】ggplot2——绘图实例ggplot2——绘图实例
时序图

Quantmod和ggplot2绘制时间序列图

library(quantmod)
library(ggplot2)
getSymbols('^SSEC',src='yahoo',from = '1997-01-01')
close <- (Cl(SSEC))
time <- index(close)
value <- as.vector(close)
yrng <- range(value)
xrng <- range(time)
data <- data.frame(start=as.Date(c('1997-01-01','2003-01-01')),end=as.Date(c('2002-12-30','2012-01-20')),core=c('jiang','hu'))
timepoint <- as.Date(c('1999-07-02','2001-07-26','2005-04-29','2008-01-10','2010-03-31'))
events <- c('证券法实施','国有股减持','股权分置改革','次贷危机爆发','融资融券试点')
data2 <- data.frame(timepoint,events,stock=value[time %in% timepoint])
p <- ggplot(data.frame(time,value),aes(time,value))
p + geom_line(size=1,colour='turquoise4')+
  geom_rect(alpha=0.2,aes(NULL,NULL,xmin = start, xmax = end, fill = core),ymin = yrng[1],ymax=yrng[2],data = data)+
  scale_fill_manual(values = c('blue','red'))+
  geom_text(aes(timepoint, stock, label = events),data = data2,vjust = -2,size = 5)+
  geom_point(aes(timepoint, stock),data = data2,size = 5,colour = 'red',alpha=0.5)
           
【R】ggplot2——绘图实例ggplot2——绘图实例

继续阅读