R语言
R语言学习笔记——扩展篇:第十九章-使用ggplot2进行高级绘图
文章目录
R语言 一、R中的四种图形系统 二、ggplot2包介绍 三、用几何函数指定图的类型 四、分组(重叠图形) 五、刻面(并排图形) 六、添加光滑曲线 七、修改ggplot2图形的外观 7.1、坐标轴 7.2、图例 7.3、标尺 7.4、主题 7.5、多重图 补——颜色集
八、保存图形
一、R中的四种图形系统
基础图形系统 :R自带grid图形系统 :
包 :grid包 特点 :
用户在图像设备上随意创建矩形区域并定义坐标系统,然后使用绘图基础单元来控制图形元素的摆放与外观。 对图形的灵活性很高,适用于软件开发者 ,但不提供生成统计图形以及完整绘图的函数,不适合数据分析师 。 lattice图形系统
包 :lattice包 特点 :
绘制网格图形,其显示一个变量的分布或者变量之间的关系,分别显示一个或多个变量的各个水平。 基于grid包创建,处理多元数据的可视化功能很强。(一般为绘图的备选方案) ggplot2图形系统
包 :ggplot2包 特点 :
最常用的图形系统 一种全面的,基于语法的,连贯一致的图形生成系统。
二、ggplot2包介绍
语法 :每一个函数修改属于自己的部分,函数与函数之间用(+)号函数串联示例 :
library( ggplot2)
ggplot( data = mtcars, aes( x= wt, y= mpg) ) +
geom_point( pch= 17 , color= "blue" , size= 2 ) +
geom_smooth( method = "lm" , color= "red" , linetype= 2 ) +
labs( title = "Automobile Data" , x = "Weight" , y = "Miles per Gallon" )
分组与小面化 :
分组 :在一个图形中显示两组或多组观测结果小面化 :在单独,并列的图形上显示观察组ggplot2包在定义组或面 时使用因子 示例 :
library( ggplot2)
mtcars$ am <- factor( mtcars$ am, levels = c( 0 , 1 ) , labels = c( "Automatic" , "Manual" ) )
mtcars$ vs <- factor( mtcars$ vs, levels = c( 0 , 1 ) , labels = c( "V-Engine" , "StraightEngine" ) )
mtcars$ cyl <- factor( mtcars$ cyl)
ggplot( data = mtcars, aes( x = hp, y = mpg, shape = cyl, color = cyl) ) +
geom_point( size = 3 ) +
facet_grid( am~ vs) +
labs( title = "Automobile Data by Engine Type" , x = "Horsepower" , y = "Miles per Gallon" )
三、用几何函数指定图的类型
步骤 :最基础的绘图步骤
一 :ggplot()函数指定要绘制的数据源和变量,ggplot(data = ,aes(x=,y=))二 :调用几何函数geom函数在视觉上表现变量,目前有37个gemo函数 常用几何函数
函数 功能 参数 geom_bar() 条形图 color、fill、alpha geom_boxplot() 箱线图 color、fill、alpha、notch、width geom_density() 密度图 color、fill、alpha、linetype geom_histogram() 直方图 color、fill、alpha、linetype、binwidth geom_hline() 水平线 color、alpha、linetype、size geom_jitter() 抖动点 color、size、alpha、shape geom_line() 线图 colorvalpha、linetype、size geom_point() 散点图 color、size、alpha、shape geom_rug() 地毯图 color、side geom_smooth() 拟合曲线图 color、fill、method、linetype、formula、size geom_text() 文字注解 详见help geom_violin() 小提琴图 color、fill、alpha、linetype geom_vline() 垂线 color、size、alpha、linetype
参数 功能 color 对点,线,填充区域的边界着色 fill 对填充区域着色,如条线和密度区域 alpha 颜透明度,0(透明)-1(不透明) linetype 图案的线条,同lty(1=实线,2=虚线,3=点,4点破折号,5=长破折号,6=双破折号) size 点的尺寸,线的宽度 shape 点的形状,同pch position 绘制诸如条形图和点等对象的位置。对条形图"dodge"将分组条形图并排,"stacked"堆叠分组条形图,"fill"垂直的堆叠分组条形图并且高度相同。对点,"jitter"将点散开分布,减少重叠 binwidth 直方图宽度 notch 方块图是否应有缺口(T/F),若两个箱的缺口互不重叠,则表明它们的中位数有显著的差异 sides 地毯图的安置(“b”=底部,“l”=左部,“t”=顶部,“r”=右部,“bl”=左下部,等等) width 箱线图的宽度
install.packages( "car" )
library( car)
ggplot( Salaries, aes( x= rank, y= salary) ) +
geom_boxplot( fill= "#00DDAA" , color = "black" , notch = T) +
geom_point( position = "jitter" , color = "blue" , alpha = .5 ) +
geom_rug( sides = "l" , color = "black" )
library( lattice)
ggplot( singer, aes( x = voice.part, y = height) ) +
geom_violin( fill = "lightblue" ) +
geom_boxplot( fill = "lightgreen" , width = .2 )
四、分组(重叠图形)
情形 :在一个图中画出两个或多组图的观察值数据类型 :因子 函数 :aes()
将变量 赋给color,fill,shape,linetype等元素,进行分组 示例1 :以学术等级分组的大学薪酬,红——助理教授,绿——副教授,蓝——教授
library( car)
ggplot( Salaries, aes( x= salary, fill= rank) ) +
geom_density( alpha = .5 )
示例2 :博士毕业年数和薪水的散点图,红——助理教授,绿——副教授,蓝——教授
ggplot( Salaries, aes( x= yrs.since.phd, y= salary, color= rank, shape= sex) ) +
geom_point( )
a <- ggplot( Salaries, aes( x= rank, fill= sex) ) +
geom_bar( position= "stack" ) +
labs( title= 'position="stack"' )
b <- ggplot( Salaries, aes( x= rank, fill= sex) ) +
geom_bar( position= "dodge" ) +
labs( title= 'position="dodge"' )
c <- ggplot( Salaries, aes( x= rank, fill= sex) ) +
geom_bar( position= "fill" ) +
labs( title= 'position="fill"' , y= "%" )
library( gridExtra)
grid.arrange( a, b, c, ncol= 3 )
五、刻面(并排图形)
概念 :分组时为了让图形重叠,刻面是为了让图形并排出现。数据类型 :因子 函数 :facet_wrap()函数和facet_grid()函数 语法与参数
语法 功能 facet_wrap(~var,ncol=n) 将每个var水平排列成n列的独立图 facet_wrap(~var,nrow=n) 将每个var水平排列成n行的独立图 facet_grid(rowvar~colvar) rowvar和colvar组合的独立图,对应为行~列 facet_grid(rowvar~.) 每个rowvar水平的独立图,配置成一个单列 facet_grid(.~colvar) 每个colvar水平的独立图,配置成一个单行
ggplot( singer, aes( height) ) +
geom_histogram( bins = 30 ) +
facet_wrap( ~ voice.part, nrow = 4 )
library( car)
ggplot( Salaries, aes( x= yrs.since.phd, y= salary, color= rank, shape= rank) ) +
geom_point( ) +
facet_grid( .~ sex)
示例3 :展示每个声部成员的身高分布,并利用核密度图水平排列,给每个声部分配不同的颜色。
ggplot( singer, aes( x= height, fill= voice.part) ) +
geom_density( ) +
facet_grid( voice.part~ .)
六、添加光滑曲线
概念 :添加光滑曲线(线性,非线性,非参数)和置信空间到散点图 中图形对象 :散点图 函数 :geom_smooth()函数 (其依赖于stat_smooth()函数 )语法与参数
语法 功能 method 绘制方法。lm=线性,glm=广义线性,smooth=loess(非参数,默认),rlm=健壮线性,gam=广义相加 formula 公式。如yx(默认),y=poly(x,n)表示n次多项式拟合,y ns(x,n)表示一个具有n给自由度的样条拟合 se 绘制置信区间(T/F),默认为T level 置信空间水平(默认95%) fullrange 指定拟合应涵盖全图(T)或仅仅是数据(F,默认)
ggplot( Salaries, aes( x= yrs.since.phd, y= salary, linetype= sex, shape= sex, color= sex) ) +
geom_smooth( method = lm, formula = y~ poly( x, 2 ) , se= F, size= 1 ) +
geom_point( size= 2 )
七、修改ggplot2图形的外观
在绘制基础图形时,可以利用par( )等函数来修改图形(第三章) 这些方法对ggplot2图形没有影响,ggplot2提供了特定的函数来改变其预先外观
7.1、坐标轴
概念 :自定义坐标轴,包括刻度线,刻度标记标签和坐标轴标签函数 :
ggplot2的函数区分x/y轴,以及轴线是否代表一个连续或者离散变量(因子)
函数 功能与参数 labs() 添加标题,改变坐标轴 scale_x_continuous()和scale_y_continuous() breaks指定刻度标记,labels指定刻度标记标签,limits控制要展示的值的范围 scale_x_discrete()和scale_y_discrete() breaks对因子的水平进行放置与排序,labels指定这些水平的标签,limits表示哪些水平应该展示 coord_flip() 颠倒x/y轴
library( ggplot2)
ggplot( Salaries, aes( x= rank, y= salary, fill= sex) ) +
geom_boxplot( ) +
scale_x_discrete( breaks = c( "AsstProf" , "AssocProf" , "Prof" ) ,
labels = c( "Assistant\nProfessor" , "Associate\nProfessor" , "Full\nProfessor" ) ) +
scale_y_continuous( breaks = c( 50000 , 100000 , 150000 , 200000 ) ,
labels = c( "$50K" , "$100K" , "$150K" , "$200K" ) ) +
labs( title = "Faculty Salary by Rank and Sex" )
7.2、图例
概念 :指出如何利用颜色,形状,尺寸等视觉特效来表示数据特征的指南图例标题 :
步骤一 :判断图例时基于颜色,形状,尺寸等具体内容(具体见**aes()**函数中的内容)进行区分的步骤二 :将fill=“mytitle”(假设以fill进行区分)添加到**labs()**函数中 图例位置
函数 :theme()函数中的legend.position参数选项
参数值 :left,top,right(默认),bottom,none(删除)或向量参数指定位置c(x,y)其中x,y(0-1),表示距离左侧边缘x底部边缘y 示例 :
library( ggplot2)
ggplot( Salaries, aes( x= rank, y= salary, fill= sex) ) +
geom_boxplot( ) +
scale_x_discrete( breaks = c( "AsstProf" , "AssocProf" , "Prof" ) ,
labels = c( "Assistant\nProfessor" , "Associate\nProfessor" , "Full\nProfessor" ) ) +
scale_y_continuous( breaks = c( 50000 , 100000 , 150000 , 200000 ) ,
labels = c( "$50K" , "$100K" , "$150K" , "$200K" ) ) +
labs( title = "Faculty Salary by Rank and Sex" , fill= "Gender" ) +
theme( legend.position = c( .1 , .8 ) )
7.3、标尺
ggplot( mtcars, aes( wt, mpg, size= disp) ) +
geom_point( shape= 21 , color= "black" , fill= "cornsilk" ) +
labs( x= "weight" , y= "Miles per Gallon" ,
title = "Bubble Chart" , size= "Engine\nDisplacement" )
示例2 :离散型标尺将带有因子水平的视觉线索(如颜色,形状,尺寸,线条类型和透明度)关联起来
函数 :scale_color_manual(values)
函数 :scale_color_brewer(palette =" name")
函数 :display.brewer.all()
ggplot( Salaries, aes( x= yrs.since.phd, y= salary, color= rank) ) +
scale_color_manual( values= c( "orange" , "olivedrab" , "navy" ) ) +
geom_point( size= 2 )
ggplot( Salaries, aes( x= yrs.since.phd, y= salary, color= rank) ) +
scale_color_brewer( palette = "Set1" ) +
geom_point( size= 2 )
7.4、主题
概念 :控制图片的整体外观,如调节字体,背景,颜色和网格线等。
函数 :theme() 示例 :
mytheme <- theme(
plot.title = element_text( face = "bold.italic" , size = 14 , color = "brown" ) ,
axis.title = element_text( face = "bold.italic" , size = 10 , color = "brown" ) ,
axis.text = element_text( face = "bold" , size = 9 , color = "darkblue" ) ,
panel.background = element_rect( fill = "white" , color = "darkblue" ) ,
panel.grid.major.y = element_line( color = "grey" , linetype = 1 ) ,
panel.grid.minor.y = element_line( color = "grey" , linetype = 2 ) ,
panel.grid.minor.x = element_blank( ) ,
legend.position = "top"
)
ggplot( Salaries, aes( x= rank, y= salary, fill= sex) ) +
geom_boxplot( ) +
labs( title = "Salary by Rank and Sex" , x= "Rank" , y= "Salary" ) +
mytheme
7.5、多重图
概念 :将多个单独的图片放在单个图形中函数 :gridExtra包中的grid.arrange()函数 语法 :
grid.arrange( figure1, figure2... , nrow= n, ncol= m, newpage = TRUE )
a <- ggplot( Salaries, aes( x= rank, fill= sex) ) +
geom_bar( position= "stack" ) +
labs( title= 'position="stack"' )
b <- ggplot( Salaries, aes( x= rank, fill= sex) ) +
geom_bar( position= "dodge" ) +
labs( title= 'position="dodge"' )
c <- ggplot( Salaries, aes( x= rank, fill= sex) ) +
geom_bar( position= "fill" ) +
labs( title= 'position="fill"' , y= "%" )
d <- ggplot( Salaries, aes( x= yrs.since.phd, y= salary, linetype= sex, shape= sex, color= sex) ) +
geom_smooth( method = lm, formula = y~ poly( x, 2 ) , se= F, size= 1 ) +
geom_point( size= 2 )
install.packages( "gridExtra" )
library( gridExtra)
grid.arrange( a, b, c, d, nrow= 2 , ncol= 2 )
补——颜色集
功能 :生成调色板,既一串颜色的集合。函数 :brewer.pal(),display.brewer.all() 语法 :
brewer.pal( 3 - x, name)
display.brewer.all( )
功能 :扩展颜色集。当颜色集里面的颜色不够时,将其进一步划分。函数 :== colorRampPalette()==语法 :
colorRampPalette( colors = c( ) ) ( n)
rev( )
colors <- colorRampPalette( rev( brewer.pal( 9 , "Blues" ) ) ) ( 255 )
library( RColorBrewer)
display.brewer.all( )
八、保存图形
ggsave(
filename,
plot = last_plot( ) ,
device = NULL ,
path = NULL ,
scale = 1 ,
width = NA ,
height = NA ,
units = c( "in" , "cm" , "mm" , "px" ) ,
dpi = 300 ,
limitsize = TRUE ,
bg = NULL ,
...
)
library( lattice)
myplot <- ggplot( singer, aes( x = voice.part, y = height) ) +
geom_violin( fill = "lightblue" ) +
geom_boxplot( fill = "lightgreen" , width = .2 )
ggsave( filename = "singers2.png" , plot = myplot, width = 5 , height = 4 , dpi = 5000 , path = "C:/Users/16748/Desktop" )