天天看點

【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——繪圖執行個體

繼續閱讀