二、R语言可视化-ggplot2工具箱

xiaoxiao2021-02-28  55

转载来自:http://www.cnblogs.com/lizhilei-123/p/6725588.html

ggplot2工具箱

 ggplot2的图层化架构让我们以一种结构化的方法来设计和构建图形,这里每一小节解决一个特定的作图问题。

1.基本图形类型

geom_area()用于绘制面积图geom_bar(stat="identity")绘制条形图,我们需要指定stat=“identity”,因为默认的统计变换会自动对值进行计数。geom_line()绘制线条图,从左到右连接geom_point()绘制散点图geom_polygon()绘制多边形geom_text()可在指定点处添加标签geom_tile()用来绘制色深图(image plot)或水平图(level plot)

使用以下代码绘制几何对象:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 >  library (ggplot2) > df <-  data.frame ( + x= c (3,1,5), + y= c (2,4,6), + lable= c ( "a" , "b" , "c" ) + ) > p <-  ggplot (df, aes (x,y))+ xlab ( NULL )+ ylab ( NULL ) > p +  geom_point ()+ labs (title= "geom_point" ) > p +  geom_bar (stat= "identity" )+ labs (title= "geom_bar(stat=\"identity\")" ) > p +  geom_line () +  labs (title= "geom_line" ) > p +  geom_area ()+ labs (title= "geom_area" ) > p+  geom_path ()+ labs (title= "geom_path" ) > p +  geom_text ( aes (label=lable))+ labs (title= "geom_text" ) > p +  geom_tile () +  labs (title= "geom_tile" ) > p +  geom_polygon () +  labs (title= "geom_polygon" )

  

2.展示数据分布

为了找到一个表现力强的视图,多次测试组距的布局细节是必不可少的。

1 2 3 4 5 > depth_dist1 <-  ggplot (diamonds ,  aes (depth)) +  xlim (40,80) > depth_dist1 +  geom_histogram ()   #左图   > depth_dist2 <-  ggplot (diamonds, aes (depth)) +  xlim (55,70) > depth_dist2 +  geom_histogram (binwidth=0.1) #右图

  

永远不要指望依靠默认的参数就能对某个具体的分布获得一个表现力强的图形(上图左),图右对x轴进行了放大,并选取了一个更小的组距宽度,binwidth=0.1

较左图揭示出了更多的细节,我们发现这个分布是轻度右偏的。

 有多种方式可以用来进行分布的跨组比较,同时绘制多个小的直方图:facets=.~var ,使用频率多边形:position="fill" 

我们使用直方图展示diamond数据中的depth变量:

1 2 3 >  library (ggplot2) > depth_dist <-  ggplot (diamonds ,  aes (depth)) +  xlim (58,68) > depth_dist +  geom_histogram ( aes (y=..density..),binwidth=0.1) +  facet_grid (cut ~ .)

  

用cut属性进行填充:

1 2 > depth_dist <-  ggplot (diamonds ,  aes (depth)) +  xlim (58,68) > depth_dist +  geom_histogram ( aes (fill=cut),binwidth=0.1,position= "fill" )

  

以下是频率多边形:freqpoly

1 > depth_dist +  geom_freqpoly ( aes (y=..density..,colour=cut),binwidth=0.1)

  

变量density基本上相当于count除以count的总和,和分布相关的许多几何对象都是以几何对象(geom)/统计变换(stat)的形式成对出现的。

一个基本几何对象结合一个统计变换,即可绘制出想要的图形。

3.处理遮盖绘制问题

散点图是研究两个连续变量间关系的重要工具。但当数据量很大时,这些点会经常出现重叠现象,掩盖真实的关系。这种问题被称为遮盖绘制,提供以下几种方法:

小规模的遮盖问题可以通过绘制更小的点加以缓解,或者使用中空的符号,下图的数据是从两个独立的正太分布中抽样所得得2000个点: 1 2 3 > df <-  data.frame (x =  rnorm (2000),y= rnorm (2000)) > norm <-  ggplot (df, aes (x,y)) > norm +  geom_point ()

  

1 > norm +  geom_point (shape=1)

  

1 > norm +  geom_point (shape= "." )    ##点的大小为像素级

  

对于更大的数据集产生的更为严重的遮盖绘制问题,我们可以使用α透明度让点呈现透明效果。在R中,最小的透明度为1/256,所以对于严重的遮盖,这种方法并不是太好。 1 2 3 > norm +  geom_point (colour =  "black" ,alpha=1/3) > norm +  geom_point (colour =  "black" ,alpha=1/5) > norm +  geom_point (colour =  "black" ,alpha=1/10)

  

转载请注明原文地址: https://www.6miu.com/read-2629168.html

最新回复(0)