张金龙的博客分享 http://blog.sciencenet.cn/u/zjlcas 物种适应性、分布与进化

博文

ggplot2绘图学习笔记: 数据,图层与统计变换

已有 14675 次阅读 2016-4-10 22:54 |系统分类:科研笔记|关键词:学者

以下内容的更新的版本已经发布,请参考 http://blog.sciencenet.cn/blog-255662-1169978.html 


主要参考 https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf


ggplot2是R软件高级绘图程序包之一, 正受到越来越多人的欢迎。  但是ggplot2的语法与R绘图的参数有根本的分别。与用函数参数控制图形的R默认的绘图程序包不同,ggplot2基于
Wilkinson, 2005书中的绘图思想, 将任何一幅统计图形看做由以下几个主要部分:

1. 数据
2. 表现数据的点, 线, 多边形, 栅格, 颜色等
3. 坐标系

具体来讲, 在ggplot2程序包中, 每一副图都是由若干元素组成, 这些图包括
data: 数据, ggplot2中所有要输入的数据, 都是data.frame
coordinate system: 坐标系, 是在二维平面上表示数据的关系。例如平面直角坐标, 极坐标, 地图投影等
geoms: 用来绘图的图标类型, 如点、线、面,多边形
aesthetics: 图标或者文字的属性, 如颜色, 形状, 透明度, 大小, 位置等。
scales: 坐标系的属性
stats: 统计变换, 描述数据要进行的转换,才能表现统计结果。例如, 平均值, 中位数,记录数等。
facets: 描述如何将图形按照不同水平分开描述, 以便同时绘制多个图形。

ggplot2程序包提供了常用的几个基本函数

qplot()  ### 主要是模仿普通的R函数,所有控制图形的信息, 都看做参数, 但这会降低绘图的灵活性。难以体现ggplot2的优势。  
ggplot() ### 构建绘图关系的最基本函数, 为了掌握ggplot2的一些技巧, 要
ggsave() ### 默认保存7×7英寸, 300dpi的图形

############################################

### 载入数据
#####
library(ggplot2)

##### 普通绘图
plot(hwy ~ cty, data = mpg)

##### qplot绘图
qplot(x = cty, y = hwy, color = cyl, data = mpg, geom = "point")

##### ggplot绘图
dev.off()
ggplot(data = mpg, aes(x = cty, y = hwy)) + ### 设置x, y以及数据
geom_point(aes(color = cyl)) +  ### 添加 点, 以及 设置 点 的颜色
geom_smooth(method = "lm") +  ### 添加拟合曲线/曲线以及置信区间
coord_cartesian() + ### 笛卡尔坐标系, 即平面直角坐标系
scale_color_gradient() + ### 图例的颜色
theme_base() +  ### 主题为base风格
scale_shape(solid = FALSE) + #### 点的类型为中空。
ggtitle("New Plot Title") +  ### 标题
xlab("New X label") +  ## 横轴
ylab("New Y label")  ## 纵轴

library(ggthemes)

标题以及坐标轴说明


### 控制圖形的label
t + labs(title =" New title", x = "New x", y = "New y") ### 或以上各项
### 控制xy座標軸的範圍
t + coord_cartesian( xlim = c(0, 100), ylim = c(10, 20))

##############################################
#### 所有在ggplot2输入的数据都应该是 data.frame()
根据绘图的目的, 选择geoms

1 一维连续数据
a <- ggplot(mpg, aes(hwy))

包括 密度图 Ribbons and area plots

频度阴影图
a + geom_area(stat = "bin")

线状频度图
a + geom_density(kernel = "gaussian")

点状频度图
a + geom_dotplot()

频度折线图
a + geom_freqpoly()

#### 单变量离散数据
b <- ggplot(mpg, aes(fl))
b + geom_bar()

###################################
###### 基本绘图元素及其属性 ##########
data(map)
c <- ggplot(map, aes(long, lat))

#### 多边形
c + geom_polygon(aes(group = group))

#### 折线图
d <- ggplot(economics, aes(date, unemploy))
d + geom_path(lineend = "butt", linejoin = "round", linemitre = 1)

#### 带状图
d + geom_ribbon(aes(ymin = unemploy - 900, ymax = unemploy + 900))

#### 线段
e <- ggplot(seals, aes(x = long, y = lat))
e + geom_segment(aes(xend = long + delta_long, yend = lat + delta_lat))

#### 长方形
e + geom_rect(aes(xmin = long, ymin = lat, xmax = long + delta_long, ymax = lat + delta_lat
))

########################################################################
########################################################################
### 二维连续数据
f <- ggplot(mpg, aes(cty, hwy))

#### 空白图形, 只生成坐标
f + geom_blank()

#### 带随机扩散的散点图
f + geom_jitter()

#### 散点图
f + geom_point()

### 分位数回归线
f + geom_quantile()

### xy轴投影
f + geom_rug(sides = "bl")

### 线性模型拟合以及置信区间
f + geom_smooth(method = "lm")

### Loess拟合趋势线以及置信区间
f + geom_smooth(method = "auto")

############################################################
################ x为离散变量, y为连续变量 ####################
############################################################
g <- ggplot(mpg, aes(class, hwy))

#### 柱状图
g + geom_bar(stat = "identity")

#### 箱线图
g + geom_boxplot()

#### 点图
g + geom_dotplot(binaxis = "y", stackdir = "center")

#### 小提琴图
g + geom_violin(scale = "area")

##############################################################
####### x为离散变量, y为离散变量
h <- ggplot(diamonds, aes(cut, color))
h + geom_jitter()

##############################################################
##############################################################
### 二维密度分布数据
data(iris)
i <- ggplot(iris, aes(Sepal.Length, Sepal.Width))

### 栅格图
i + geom_bin2d(binwidth = c(5, 0.5))

### 等高线密度图
i + geom_density2d()

### 六角形密度图
i + geom_hex()

#######################################################
######## 有时间序列的连续变量 ############################
j <- ggplot(economics, aes(date, unemploy))

### 阴影图
j + geom_area()

### 折线图
j + geom_line()

### 阶梯图
dev.off()
j + geom_step(direction = "hv")


#######################################################
############# 误差的表示 ################################
df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)
k <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))

#### 误差箱图
k + geom_crossbar(fatten = 2)

#### 误差线图(带横线)
k + geom_errorbar()

#### 误差线图(不带横线)
dev.off()
k + geom_linerange()

####  带误差线的点图
k + geom_pointrange()


#######################################################################
##### 地图 ###########

data <- data.frame(murder = USArrests$Murder,
state = tolower(rownames(USArrests)))
map <- map_data("state")
l <- ggplot(data, aes(fill = murder))

l + geom_map( aes(map_id = state), map = map ) + expand_limits( x = map$long, y = map$lat )

#######################################################################
###### 三个变量

seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2))
m <- ggplot(seals, aes(long, lat))

#### 等高线图
m + geom_contour(aes(z = z))

#### 栅格图
m + geom_raster(aes(fill = z), hjust=0.5, vjust=0.5, interpolate=FALSE)

####
 m + geom_tile(aes(fill = z))



####################################################################
############ 统计变换 ######################
############ 如果没有指定统计变化, 则ggplot的geom调用默认的统计变换方法, 以绘图图形
############  
############

a + geom_bar(stat = "bin")
### stat以及geom都可以使用 stat参数生成一个新的图层

如 stat_bin(geom = "bar")
和 geom_bar(stat = "bin") 两者等价

###################################################
####  一维概率密度统计变换参数的设定
a + stat_bin(binwidth = 1, origin = 10)
### a + stat_bindot(binwidth = 1, binaxis = "x") ### Not available
a + stat_density(adjust = 1, kernel = "gaussian")

###################################################
#### 二维概率密度统计变换参数的设定
f + stat_bin2d(bins = 30, drop = TRUE)
f + stat_binhex(bins = 30)
f + stat_density2d(contour = TRUE, n = 100)

###################################################
#### 三维数据的统计变换参数设定
#### 等高线图
m + stat_contour(aes(z = z))

#### 线段图
m+ stat_spoke(aes(radius= z, angle = z))

#### 六角形图
m + stat_summary_hex(aes(z = z), bins = 30, fun = mean)

#### 栅格图
m + stat_summary2d(aes(z = z), bins = 30, fun = mean)

####################################################
### 组间比较#
### 箱线图
g + stat_boxplot(coef = 1.5)

### 提琴图参数设定
g + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area")

#### 累积曲线
f + stat_ecdf(n = 40)

#### 分位数曲线图
f + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x), method = "rq")

#### Loess回归以及置信区间统计变换的参数设定
f + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80, fullrange = FALSE, level = 0.95)

#####################################################
#### 绘制dnorm的概率密度分布
ggplot() + stat_function(aes(x = -3:3), fun = dnorm, n = 101, args = list(sd=0.5))

#### 绘制散点图
f + stat_identity()

#### 绘制qq图
ggplot() + stat_qq(aes(sample=1:100), distribution = qt, dparams = list(df=5))

#### 绘制散点图, 点的大小为该点数据出现的次数
f + stat_sum()

#### 带误差线的点图
f + stat_summary(fun.data = "mean_cl_boot")

#### 散点图
f + stat_unique()

################################################################
########## 图例 ##################
########## ggplot2 的图例与图形是一个整体, 设定图例的参数, 图例会更改,
##########  设定图形的参数, 图例会自动更改。

scale 控制图形中的颜色,文字显示, 图例中的图形

dev.off()

n <- b + geom_bar(aes(fill = fl))
n

##### 柱状图设定颜色, 各组名称, 图例中各组名, 类别划分
n + scale_fill_manual(
   values = c("skyblue", "royalblue", "blue", "navy"),
   limits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", "r"),
   name = "fuel", labels = c("D", "E", "P", "R"))
   

###################################################################
#### 控制图形scale的几个函数

#### 按照数据的类别, 分为

scale_*_continuous()
scale_*_discrete()
scale_*_identity()
scale_*_manual(values = c())

这几个函数的参数主要为
alpha, 透明度
color, 颜色序列
fill, 颜色序列
linetype, 线段类型
shape, 点的形状
size, 点的大小

#######################################################################
##### 坐标轴变换
##### x轴显示为日期
scale_x_date(labels = date_format("%m/%d"), breaks = date_breaks("2 weeks"))

##### x轴显示未日期和时间
scale_x_datetime()

##### x轴转换为以10为底的对数
scale_x_log10()

##### x轴逆向显示
scale_x_reverse()

##### x轴平方根变换
scale_x_sqrt()

############################################################
############ ggplot2中的颜色 ################################
n <- b + geom_bar(aes(fill = fl))

#### R中调色板
n + scale_fill_brewer(palette = "Blues")

#### R中的灰色梯度显示柱状图
n + scale_fill_grey( start = 0.2, end = 0.8, na.value = "red")

####通过 scale_fill_gradient显示颜色过渡
o <- a + geom_dotplot(aes(fill = ..x..))
o + scale_fill_gradient( low = "red", high = "yellow")

####通过scale_fill_gradient2显示颜色过渡
o + scale_fill_gradient2( low = "red", hight = "blue", mid = "white", midpoint = 25 )

##### 选择颜色序列
o + scale_fill_gradientn(colours = terrain.colors(6) )

其他可以选择的颜色: rainbow(), heat.colors(), topo.colors(), cm.colors(), RColorBrewer::brewer.pal()

##########################################################
############ 图标形状的选择#################################
##### 点图标的选择
p <- f + geom_point(aes(shape = fl))

##### 显示空心图标
p + scale_shape(solid = FALSE)

##### 指定点图标
p + scale_shape_manual(values = c(3:7))

################################################
########### 图标大小的设定 ##########################

#### 设定图标大小与变量的关系
q <- f + geom_point(aes(size = cyl))

#### 设定图标大小的范围
q + scale_size_area(max = 6)


#######################################################################
########### ggplot2中的坐标系 ##########################################
r <- b + geom_bar()

### 平面直角坐标系
r + coord_cartesian(xlim = c(0, 5))

### 横轴, 纵轴以固定比例显示
r + coord_fixed(ratio = 1/2)

### 横轴纵轴调换
r + coord_flip()

### 极坐标, 适用于绘制饼图
r + coord_polar(theta = "x", direction=1 )

### 横轴, 纵轴的变换, 如 log, sqrt等
r + coord_trans(ytrans = "sqrt")

### 地图投影变换
z + coord_map(projection = "ortho", orientation=c(41, -74, 0))

###############################################################
###############################################################
##################### 柱状图的叠加以及比较 #######################

s <- ggplot(mpg, aes(fl, fill = drv))

#### 并排排列
s + geom_bar(position = "dodge")

#### 堆叠排列
s + geom_bar(position = "stack")

### 按百分比堆叠排列, 各柱子等高
s + geom_bar(position = "fill")

################################################################
####### 散点图的随机化 ##########
#### 在每个点的x,y方向上都加上较小的随机值, 以便点能散开。
f + geom_point(position = "jitter")


#################################################################
####### ggplot2的主题 ############################################
theme_bw()
theme_grey()
theme_classic()
theme_minimal()

#### ggthemes的主题
#### https://github.com/jrnold/ggthemes
library(ggtheme)
theme_base()

#################################################################

#################################################################
###按照因子组合绘制多图#############################################
t <- ggplot(mpg, aes(cty, hwy)) + geom_point()

t + facet_grid(. ~ fl) ### 按照列, 排列不同 fl
t + facet_grid(year ~ .) ### 按照行, 排列不同 year
t + facet_grid(year ~ fl) ### 行为 year, 列为 fl
t + facet_wrap(~ fl) #### 设定显示为几行几列, nrow = NULL, ncol = NULL

#### 每幅图中的xy的范围可以自由确定
t + facet_grid(y ~ x, scales = "free")

#### 每幅图小标题的显示
t + facet_grid(. ~ fl, labeller = label_both)
t + facet_grid(. ~ fl, labeller = label_bquote(alpha ^ .(x)))
t + facet_grid(. ~ fl, labeller = label_parsed)

#### 标题文字, 坐标轴文字的显示
t + ggtitle("New Plot Title")  ### 标题
t + xlab("New X label")        ### x轴标题
t + ylab("New Y label")        ### y轴标题
t + labs(title =" New title", x = "New x", y = "New y") ### 同时设定标题, xy轴标题

#### 图例位置
 t + theme(legend.position = "bottom") ###"bottom", "top", "left", or "right"

t + guides(color = "none")
t + scale_fill_discrete(name = "Title", labels = c("A", "B", "C"))


##### 设定显示的范围
### 显示某一范围
t + coord_cartesian(xlim = c(0, 100), ylim = c(10, 20))

### 显示xy数据
t + xlim(0, 100) + ylim(10, 20)



https://m.sciencenet.cn/blog-255662-969223.html

上一篇:克里格空间插值Kriging及其在R的实现
下一篇:在R中绘制进化树:ggtree学习笔记

0

该博文允许注册用户评论 请点击登录 评论 (3 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-19 13:30

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部