R语言绘图系列:
- R语言可视化及作图1--基础绘图(par函数,散点图,盒形图,条形图,直方图)
- R语言可视化及作图2--低级绘图函数
- R语言可视化及作图3--图形颜色选取
- R语言可视化及作图4--qplot和ggplot2美学函数
- R语言可视化及作图5--ggplot2基本要素和几何对象汇总
一. 点图
ggplot2绘制点图使用的是geom_point()
标度函数scale:
标度控制着数据到图形属性的映射,标度将我们的数据转化为视觉上可以感知的东西,比如大小、位置、颜色、形状等。标度也为我们提供了读图时所使用的工具,比如说坐标轴和图例。总的来说,可以称为引导元素。标度函数控制元素的属性,可以理解为图形的遥控器,可以用它来调整画布大小、颜色等等。此前学的shape,color,size等参数和标度函数相比显得不够灵活。
图形属性 | 离散型 | 连续型 |
---|---|---|
颜色(colour)和填充色(fill) | brewer、grey、hue、identity、manual | gradient、gradient2、gradientn |
位置(position)(x,y) | discrete | continuous、date、datetime、log10、sqrt、reverse |
形状(shape) | shape、identity、manual | |
线条类型(line type) | linetype、identity、manual | |
大小(size) | identity、manual | size |
-
表格中的加粗:默认参数
-
用法:scale_+图形属性名称(例如,colour_、shape_或x_)+标度的名称(例如,gradient、hue 或manual)。
比如:离散性数据的颜色图形属性默认标度名为scale_colour_hue(),形状图形属性标度为scale_shape_shape()。使用?或者help()可以查看相关参数及具体用法。 -
scale_x_XXX、scale_y_XXX 是控制x、y 轴的标度,用于设置x、y 轴的显示标签、显示范围、刻度上的值等等。XXX 主要有continuous、data、datatime、discrete、log10、sqrt 等等。
对于图例的标度,如果图例是控制着颜色属性colour,那么使用 -
scale_colour_XXX 可以设置这个图例的属性(比如标签、显示的值)。类似的还有scale_size_XXX、scale_fill_XXX、scale_shape_XXX 等等,具体用法以及参数请查看帮助文档。
1. 点的颜色
- scale_colour_gradient参数及其几个孪生参数可以设置颜色
library(ggplot2)
#生成演示数据集
df <- data.frame(
x=runif(100),
y=runif(100),
z1=rnorm(100),
z2=abs(rnorm(100))
)
ggplot(df,aes(x,y))+geom_point(aes(colour=z2))

ggplot(df,aes(x,y))+geom_point(aes(colour=z1))+scale_color_gradient2()

ggplot(df,aes(x,y))+geom_point(aes(colour=z1))+scale_color_gradient(low = 'green',high='red')

ggplot(df,aes(x,y))+geom_point(aes(colour=z1))+scale_color_gradientn(colours = rainbow(8))

- 自定义颜色:scale_colour_manual函数
p <- ggplot(mtcars,aes(mpg,wt))+geom_point(aes(color=factor(cyl)))
p+scale_color_manual(values=c('red','blue','green'))

2. 点的形状
- 设置点的形状:scale_shape函数
data('diamonds')
dsmall <- diamonds[sample(1:nrow(diamonds),1000),] #从diamonds数据集中取1000行做演示
ggplot(dsmall,aes(carat,price))+geom_point(aes(shape=cut))
#Warning message:
#Using shapes for an ordinal variable is not advised

ggplot(dsmall,aes(carat,price))+geom_point(aes(shape=cut))+scale_shape(name='diamonds cut',solid = FALSE)
#图中变成了空心点,图例也进行了修改,name设置的是图例名称

- 自定义点的形状:scale_shape_manual
ggplot(dsmall,aes(carat,price))+geom_point(aes(shape=cut))+scale_shape_manual(name='diamonds cut',values = c(1:5))
#1:5和基础绘图包中的形状是一一对应的

3. 点的大小
- scale_size函数设置点的大小
p <- ggplot(mpg,aes(displ,hwy,size=hwy))+geom_point()
p+scale_size(name='hwy size',breaks = c(12,24,44),
labels = c('low','middle','high'))
#break是对原始数据进行切分,相应的标签是low middle high。但是hwy是一个连续型变量,因而点的大小并不是和这三个标签一一对应的,而是和数值大小有关。

- p+scale_radius() #将大小传至圆点的半径
df <- data.frame(x=c(0:10),y=c(20:30)) #第一个点横坐标为0
ggplot(df,aes(x=x,y=y,size=x))+geom_point()+scale_size_area()

二. 条形图
条形图最主要的功能是展示一个离散型数据
1. geom_bar函数绘制条形图
library(ggplot2)
g <- ggplot(mpg,aes(class))
g+geom_bar()
#绘出的图横轴是不同的class,纵轴是class的计数。

g+geom_bar(aes(weight=displ))+ylab('count on displ')
#使用weight来让class基于其他变量进行计数 如displ,并对y轴标签进行设置

2. 改变条图堆栈方式(position参数)
data('diamonds') #调用钻石数据集
set.seed(2021)
dsmall <- diamonds[sample(nrow(diamonds),1000),]
p <- ggplot(dsmall,aes(x=color,fill=cut))
p+geom_bar(position = 'stack')
#position参数默认是stack,也就是堆栈的意思

p+geom_bar(position = 'dodge')
#dodge是挨着,相邻的意思

p+geom_bar(position = 'fill')
#展示计数的百分比

3. 改变图形堆栈中颜色的填充方式
scale_fill_brewer 调色板函数
p+geom_bar(position = 'dodge')+scale_fill_brewer(type = 'qual')
#这里的type和RcolorBrewer里的三种type(seq, div, qual)是一样的,type=qual是离散型颜色

4. 绘制error bar
geom_errorbar()
geom_crossbar()
geom_linerange() 绘制线段
geom_pointrange() 绘制点
#生成数据集
dff <- data.frame(mean_value=c(18,20,23,16,24,15),
group=factor(LETTERS[1:6]),
sd_value=c(1.4,1.7,2.1,1.2,1.9,1.0))
dff$lower=with(diff,mean_value-1.5*sd_value)
dff$upper=with(diff,mean_value+1.5*sd_value)
p <- ggplot(dff,aes(group,mean_value))+geom_bar(position = 'dodge',fill='skyblue',stat='identity')
p+geom_errorbar(aes(ymin=lower,ymax=upper),position = 'dodge',width=0.2,color='red')

pointrange:点画线
pp <- ggplot(dff,aes(group,mean_value))+geom_point()+geom_line()
pp+geom_pointrange(aes(ymin=lower,ymax=upper),color='red')

gp <- ggplot(dff,aes(x=mean_value,y=group)) #注意,x和y互换了
gp+geom_errorbarh(aes(xmin=lower,xmax=upper),height=0.2,color='sky blue')+geom_point(color='blue')
#errorbarh就是水平errorbar的意思

三. 盒形图:geom_boxplot函数
首先绘制一张盒形图
library(ggplot2)
p <- ggplot(mpg,aes(class,hwy))
p+geom_boxplot()

在图上显示出观测值
p+geom_boxplot()+geom_point(color='red') #使用geom_point描绘出点

值得注意的是,图上点的多少并不能完全反应原始数据的多少,因为有的点可能因为点过于密集就会被覆盖,看起来是一个点,其实可能是多个点。
因此可以使用geom_jitter函数将不同的点区分开(jitter是震荡散点),width设置如果遇到相同的点,点向左右方平移的距离。alpha设置透明度。
p+geom_boxplot()+geom_jitter(width=0.2, alpha=0.5, color='orange')

黑色点是离群点
还可以绘制卡槽图
p+geom_boxplot(notch=TRUE)

varwidth参数会根据该水平下观测值的个数(n值)改变盒形图的宽度。(这里宽度去的不是观测个数的绝对值,而是平方根,以缩小差距。)
p+geom_boxplot(varwidth = TRUE)

给盒子上色
p+geom_boxplot(fill = 'sky blue',color='red')

分组盒形图,用不同颜色区分
p+geom_boxplot(aes(color=drv))

画水平的盒形图
使用coord_flip函数(坐标轴翻转函数)
p+geom_boxplot()+coord_flip()

4. 直方图:geom_histogram函数
绘制一张直方图
data('diamonds') #调用钻石数据集
set.seed(2021)
dsmall <- diamonds[sample(nrow(diamonds),1000),]
ggplot(dsmall,aes(carat))+geom_histogram(fill='darkorchid4')

bins可以设置直方图条柱的数目,默认为30。当bins和binwidth(设置条柱宽度)同时设置时,默认以binwidth为准。
ggplot(dsmall,aes(carat))+geom_histogram(fill='darkorchid4',bins = 45)+xlim(0,3)
#将条柱数目设置为45,xlim将x轴范围限定0-3

ggplot(dsmall,aes(carat))+geom_histogram(fill='darkorchid4',bins = 300)
#切分了300个条柱

ggplot(dsmall,aes(carat))+geom_histogram(fill='darkorchid4',binwidth = 0.01)
#每个条柱的宽度被binwidth设置为0.01

新加入变量cut,根据新变量在price水平上进行一个计数
ggplot(dsmall,aes(price,fill=cut))+geom_histogram(binwidth = 500)

y轴由count变为density,绘制概率密度
ggplot(dsmall,aes(price,..density..))+geom_histogram(fill='brown1',color='black')

注意下面density的写法,前后都要加..
绘制概率密度曲线:geom_density函数
ggplot(dsmall,aes(depth,fill=cut,color=cut))+geom_density(alpha = 0.1)+xlim(55,70)

堆栈密度概率曲线
ggplot(dsmall,aes(depth,fill=cut,fill=cut))+geom_density(position = 'stack')

五. 线图 geom_line函数
geom_line/geom_path/geom_step
绘制一个简单的线图
ggplot(economics,aes(date,unemploy))+geom_line(color='red')
#使用economics数据集,反映时间和失业率的变化

绘制点线图,点和线需要分别添加。
df <- data.frame(x=c(1:10),y=sample(10:30,10))
ggplot(df,aes(x,y))+geom_point(color='blue')+geom_line(color='red')

如上图,线在点之上,是因为先投射了点,又投射了线。
ggplot(df,aes(x,y))+geom_line(color='red')+geom_point(color='blue')

先投射线,点就出现在了线之上。
dff <- data.frame(x=c(1:10),y=c(1:10))
ggplot(dff,aes(x,y,color=x))+geom_line()+geom_point(color='blue')

线的颜色出现了渐变
ggplot(economics_long,aes(date,value01))+geom_line(aes(linetype=variable,color=variable))
#改变线型

geom_smooth函数:绘制拟合曲线
a=ggplot(mpg,aes(displ,hwy))+geom_point()+geom_smooth(span=0.2)
a #span是曲线的平滑度,a的平滑度是0.2,黑色阴影是95%置信区间

b=ggplot(mpg,aes(displ,hwy))+geom_point()+geom_smooth(span=0.8)
b #平滑度是0.8,值越大,曲线越平滑

c=ggplot(mpg,aes(displ,hwy))+geom_point()+geom_smooth(method = 'lm',color='red')
c #使用的是lm线性回归

methods还有其他的方法,如glm:广义线性模型;losses:纯粹平滑;gam:广义加性模型等等(lm和glm最常用)
mydata <- data.frame(time=seq(2000,2016,1),
m_value=rnorm(17,20,5),
sd_value=runif(17,1,3))
ggplot(mydata,aes(time,m_value))+geom_line(color='deeppink4',size=1)+
geom_line(aes(time,m_value+1.96*sd_value),color='black',linetype=2)+
geom_line(aes(time,m_value-1.96*sd_value),color='black',linetype=2)+
geom_ribbon(aes(time,ymin=m_value-1.96*sd_value,ymax=m_value+1.96*sd_value),fill='light green',alpha=0.3)
#geom_line绘制了三条线,中间是均值曲线,两边则分别是95%置信区间的上限和下限曲线,linetype=2是虚线
#geom_ribbon函数:绘制色带

geom_hline绘制水平线,geom_vline绘制垂直线。xintercept和yintercept是截距,slope是斜率。
ggplot(mpg,aes(displ,hwy))+geom_point(color='deeppink2')+
geom_hline(yintercept=c(15,25,35),linetype=2,color='black')+
geom_vline(xintercept=c(3,4.5,6),linetype=2,color='green')+
geom_abline(slope = 6,intercept = 5,color='blue')

网友评论