R ggplot学习笔记1
R 可视化学习笔记
记参数挺费劲的,还是用的时候查官方文档吧,现在记个大概就行吧~
1.ggplot2分层次绘图
1.1 核心理念
- 把绘图与数据分离,把数据相关的绘图与数据无关的绘图分离,按图层作图。ggplot2可以把绘图拆分成多个图层,且能够按照顺序创建多重图形
- 使用ggplot2包创建图形时,每个图形都是由函数ggplot()创建的,提供绘图的数据和映射
- 数据(data):数据框对象
- 映射(mapping):由aes()函数来设置映射
1.2 ggplot2绘图组件
列几种常见的部件
几何对象(geom)
统计变换(stats)
标度(scale)
坐标系(coord)
分面(facet)
主题(theme)

这些组件之间是通过“+”, 以图层(layer)的方式来粘合构图的,可以这样理解ggplot2中的图层:每个图层可以代表一个图形组件, 这些图形组件以图层的方式叠加在一起构成一个绘图的整体,在每个图层中的图形组件又可以分别设定数据、映射或其他相关参数,因此组件之间又是具有相对独立性的。越后面的图层越高。
例如
1.3 data and aes()
数据和映射
ggplot(data = NULL, mapping = aes())
1.3.1 数据
- data: 用于指定要用到的数据源,必须使数据框类型
1.3.2 aes()
用来设定图形属性的
- mapping:使用aes()函数指定每个变量的角色,除x和y之外的其他参数,例如,size、color、shape等,必须采用name=value的形式。
-在ggplot中设置的映射是默认映射关系,其他图层中可以继承该映射关系,或修改映射关系。也就是说,ggplot设置是全局的,其他图层可以继承或者进行修改参考 - aes()中常见属性包括
- x和y:用于指定x轴和y轴的变量
- color:映射点或线的颜色
- fill:映射填充区域的颜色
- linetype:映射图形的线形(1=实线、2=虚线、3=点、4=点破折号、5=长破折号、6=双破折号)
- size:点的尺寸和线的宽度
- shape:映射点的形状

- group:默认情况下ggplot2把所有观测点分为了一组, 如果需要把观测点按额外的离散变量进行分组处理, 必须修改默认的分组设置
- 如果需要把观测点按指定的因子进行分组处理,必须修改默认的分组设置
- 分组也可以通过映射把视觉特征(shape、color、fill、size和linetype等)设置为变量来实现分组,分组通常使用因子来实现,这就要求在数据集中存在因子变量,用于对数据分类,实现图形的分组
-group设置col区分不同属性
ggplot(mtcars, aes(wt, mpg,col=cyl)) +
geom_point(shape=1, size=4)

区分一下col和fill,一个是空心的,一个是实心的,fill是填充嘛
举个栗子
设置fill区分不同的属性
ggplot(mtcars, aes(x = wt, y = mpg, fill = cyl)) +
geom_point(shape = 21, size = 4,alpha=0.6)

factor
若变量是连续型的,则需要将变量离散化,因此factor出现了,否则报错Error: A continuous variable can not be mapped to shape
ggplot(mtcars, aes(x = mpg, y = qsec, col = cyl, shape = am, size = (hp/wt))) +
geom_point()

> diamonds
# A tibble: 1,000 x 10
carat cut color clarity depth table price x y z
* <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1 0.31 Ideal G VS1 62.4 55 802 4.35 4.33 2.71
2 1.5 Good G SI2 64.3 57 8190 7.29 7.2 4.66
3 0.9 Premium H VS2 62.8 58 3810 6.17 6.13 3.86
4 1.01 Ideal F VS2 60.9 58 7411 6.43 6.47 3.93
5 0.33 Very Good D VS1 63.2 56 1109 4.45 4.44 2.81
6 1.08 Ideal G VS1 62 55 6779 6.62 6.57 4.09
7 1.07 Premium G SI1 61.6 58 5453 6.6 6.56 4.05
8 0.33 Premium H VS1 59.5 59 743 4.53 4.48 2.68
9 0.44 Ideal H IF 62 57 1255 4.87 4.91 3.02
10 1 Premium G VS1 58.6 61 6989 6.57 6.5 3.83
# ... with 990 more rows
# Create the object containing the data and aes layers: dia_plot
dia_plot <- ggplot(diamonds, aes(x = carat, y = price))
# Add the same geom layer, but with aes() inside
dia_plot + geom_point(aes(color = clarity))

放一组对比代码查看各个参数的作用
# Map cyl to size
ggplot(mtcars, aes(x = wt, y = mpg, size = cyl)) +
geom_point()
# Map cyl to alpha
ggplot(mtcars, aes(x = wt, y = mpg, alpha = cyl)) +
geom_point()
# Map cyl to shape
ggplot(mtcars, aes(x = wt, y = mpg, shape = cyl)) +
geom_point()
# Map cyl to labels
ggplot(mtcars, aes(x = wt, y = mpg, label = cyl)) +
geom_text()




1.3.3fill属性
直接使用fill属性设置填充,是无效的,若不在aes里面设置color,需要结合fill和子图层的color,直接在子图层设置color属性值,也是无效的,因此需要分组
这里需要复习一下数据处理的的gather函数,由宽面板变为长面板
my_color <- "#4ABEFF"
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(color = my_color)
# Set the fill aesthetic; color, size and shape attributes
ggplot(mtcars, aes(x = wt, y = mpg, fill = cyl)) +
geom_point(size = 10, shape = 23, color = my_color)


1.4 geom_xxx() and stat()

1.4.1 geom_xxx
- 几何对象控制图层的渲染和生成的图像类型,例如,geom_point()会生成散点图,而geom_line会生成折线图。
- 函数ggplot()可以设置图形,但是没有视觉输出,需要使用一个或多个几何函数向图形中添加几何对象(geometric,简写为geom),包括点(point)、线(line)、条(bar)等,而添加几何图形的格式十分简单,通过符号“+”把几何图形添加到plot中
ggplot()+
geom_xxx()
- geom_text()添加文本
- geom_bar()条形图
- position
geom_bar()里面的位置调整参数
-identity(默认) - jitter
- stack 堆叠
- fill 堆叠显示百分比
- dodge 并列
- posn_d overlab 叠加
- position
- geom_points() 散点图==scatter
举个栗子
cyl.am +
geom_bar(position="stack")
# Fill - show proportion
cyl.am +
geom_bar(position = "fill")
# Dodging - principles of similarity and proximity
cyl.am +
geom_bar(position ="dodge")
# Clean up the axes with scale_ functions
val = c("#E41A1C", "#377EB8")
lab = c("Manual", "Automatic")
cyl.am +
geom_bar(position = "dodge") +
scale_x_discrete("Cylinders") +
scale_y_continuous("Number") +
scale_fill_manual("Transmission",
values = val,
labels = lab)




ggplot(mtcars, aes(x = cyl, fill = am)) +
geom_bar(position = posn_d, alpha = 0.6)
- geom_histgram 柱状图
ggplot(mtcars, aes(mpg)) +
geom_histogram(aes(y = ..density..), binwidth = 1, fill = "#377EB8")
- geom_freqpoly 柱状图的曲线图
ggplot(mtcars, aes(mpg, color = cyl)) +
geom_freqpoly(binwidth = 1)
- lines
时间序列图 - geom_rect()
ggplot(economics, aes(x = date, y = unemploy/pop)) +
geom_rect(data = recess,
aes(xmin = begin, xmax = end, ymin = -Inf, ymax = +Inf),
inherit.aes = FALSE, fill = "red", alpha = 0.2) +
geom_line()
1.4.2 geom_xxx常见参数
- color:对点、线和填充区域的边界进行着色
- fill:对填充区域着色
- alpha:演示的透明度,从透明(0)到不透明(1)
- linetype:图案的线条(1=实线、2=虚线、3=点、4=点破折号、5=长破折号、6=双破折号)
- size:点的尺寸和线的宽度
- shape:点的形状(和par()函数的pch参数相同)
- position:绘制条形图和点等对象的位置
举个栗子
# Scatter plot: clarity (x), carat (y), price (color)
ggplot(diamonds, aes(x = clarity, y = carat, color = price)) +
geom_point(alpha = 0.5)
# Dot plot with jittering
ggplot(diamonds, aes(x = clarity, y = carat, color = price)) +
geom_point(alpha = 0.5, position = "jitter")
设置position之后,明显看清了,因该是调整了刻度


- binwidth:分箱的宽度
- notch:表示方块图是否应该有缺口
- sides:地毯图的位置("b"=底部、"l"=左部、"r"=右部、"bl"=左下部,等)
- width:箱线图的宽度
label and shape are only applicable to categorical data.
1.4.3 stat
- 统计变换是对数据进行统计,通常以某种方式对数据信息进行汇总, 例如通过stat_smooth()添加光滑曲线。
- 每一个几何对象都有一个默认的统计变换, 并且每一个统计变换都有一个默认的几何对象
1.4.4 geom_jitter()
在R中散点图的时候会经常出现,点重合比较严重的现象,这对我们寻找数据规律或者观察数据有很大的干扰。因此R中,可以用geom_jitter()函数来调整,消除点的重合。
geom_jitter(mapping = NULL, data = NULL, stat = "identity", position = "jitter", ..., width = NULL, height = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)
就参数而言,geom_jitter()和其他函数差别不大,特别的两个参数是width,height
- width 用于调节点波动的宽度
- height 用于调节点波动的高度
例如有一个散点图

经过处理之后,明显不重合了
ggplot(mtcars, aes(x = mpg, y = 0)) +
geom_jitter()
# 2 - Add function to change y axis limits
ggplot(mtcars, aes(x = mpg, y = 0)) +
geom_jitter() +
scale_y_continuous(limits = c(-2,2))#设置y轴起始刻度,这是连续变量刻度


1.5 scale
- 标度:标度控制着数据到图形属性的映射,更重要的一点是标度将我们的数据转化为视觉上可以感知的东西, 如大小、颜色、位置和形状。所以通过标度可以修改坐标轴和图例的参数
scale
1.5.1常见scale
- labs()标签 xlab() ylab() ggtitle()
- 图形选项(颜色、size、形状、线形等)
自定义图形选项
scale_colour_manual()
scale_fill_manual()
scale_size_manual()
scale_shape_manual()
scale_linetype_manual()
scale_alpha_manual()
scale_discrete_manual() - 坐标轴
标度是区分离散和连续变量的,标度用于将连续型、离散型和日期-时间型变量映射到绘图区域,以及构造对应的坐标轴
1.6 坐标轴
坐标系统确定x和y美学如何组合以在图中定位元素。默认的坐标系是笛卡尔坐标系,coord_cartesian(),笛卡尔坐标系是最常用的坐标系,函数coord_flip() 用于反转笛卡尔坐标系,把x轴和y轴对调,一般采用默认的额
1.7 facet
这个参数一开始我不太懂是用来做什么的
facet_grid(rows = NULL, cols = NULL, scales = "fixed",
space = "fixed", shrink = TRUE, labeller = "label_value",
as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE,
facets = NULL)
rows, cols
A set of variables or expressions quoted by vars() and defining faceting groups on the rows or columns dimension. The variables can be named (the names are passed to labeller).
For compatibility with the classic interface, rows can also be a formula with the rows (of the tabular display) on the LHS and the columns (of the tabular display) on the RHS; the dot in the formula is used to indicate there should be no faceting on this dimension (either row or column).
数据框的行列,变量scales
- "fixed" x和y的标度在所用平面中都相同,在不同分面中进行固定
- "free_x" 固定x轴,y轴自由变化
- "free_y" 固定y轴,x轴自由变化
- "free" x和y的标度在每个版面都可以变化
space
If "fixed", the default, all panels have the same size. If "free_y" their height will be proportional to the length of the y scale; if "free_x" their width will be proportional to the length of the x scale; or if "free" both height and width will vary. This setting has no effect unless the appropriate scales also vary.可以根据数据的不同分组, 将图形按照水平或者垂直方向进行分割,同时可以共享x轴或者y轴
分组和刻面都用于对数据分组,便于观察各自的规律、趋势和模式,不同的是,分组是把图形绘制到一个大的图形中,通过美学特征来区分,而刻面是把图形绘制到不同的网格中。
刻面是在一个画布上分布多幅图形,这一过程需要先把数据划分为多个子集, 然后把每个子集依次绘制到画布的不同面板中
- facet_grid()在网格分面
- 根据数据不同可以绘制共用x轴或者y轴的子图,python中的subplots,
- facet_grid()在网格分面
str(iris.tidy)
# Think about which dataset you would use to get the plot shown right
# Fill in the ___ to produce the plot given to the right
ggplot(iris.tidy, aes(x = Species, y = Value, col = Part)) +
geom_jitter() +
facet_grid(. ~ Measure)
> str(iris.tidy)
'data.frame': 600 obs. of 4 variables:
$ Species: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Part : chr "Sepal" "Sepal" "Sepal" "Sepal" ...
$ Measure: chr "Length" "Length" "Length" "Length" ...
$ Value : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...

- facet_wrap()将一维面板的丝带缠绕成二维,封装分面,自动分成2x4, 3x2等版块
- vars()引用分面变量
具体可以参考
1.8 theme
主题
2 为何使用ggplot
因为省代码
R ggplot学习笔记1的更多相关文章
- R语言学习笔记之: 论如何正确把EXCEL文件喂给R处理
博客总目录:http://www.cnblogs.com/weibaar/p/4507801.html ---- 前言: 应用背景兼吐槽 继续延续之前每个月至少一次更新博客,归纳总结学习心得好习惯. ...
- R语言学习笔记(二)
今天主要学习了两个统计学的基本概念:峰度和偏度,并且用R语言来描述. > vars<-c("mpg","hp","wt") &g ...
- R语言学习笔记:小试R环境
买了三本R语言的书,同时使用来学习R语言,粗略翻下来感觉第一本最好: <R语言编程艺术>The Art of R Programming <R语言初学者使用>A Beginne ...
- R语言学习笔记 之 可视化地研究参议员相似性
基于相似性聚类 很多时候,我们想了解一群人中的一个成员与其他成员之间有多么相似.例如,假设我们是一家品牌营销公司,刚刚完成了一份有潜力新品牌的研究调查问卷.在这份调查问卷中,我们向一群人展示了新品牌的 ...
- R绘图学习笔记
R软件作图学习,首先为了体验方便,我使用的R中MASS包中的自带数据集,首先加载该包 > library(MASS) 加载数据集,该数据集事保险数据统计 > data("Insu ...
- R语言学习笔记:基础知识
1.数据分析金字塔 2.[文件]-[改变工作目录] 3.[程序包]-[设定CRAN镜像] [程序包]-[安装程序包] 4.向量 c() 例:x=c(2,5,8,3,5,9) 例:x=c(1:100) ...
- R语言学习笔记:使用reshape2包实现整合与重构
R语言中提供了许多用来整合和重塑数据的强大方法. 整合 aggregate 重塑 reshape 在整合数据时,往往将多组观测值替换为根据这些观测计算的描述统计量. 在重塑数据时,则会通过修改数据的结 ...
- R语言学习笔记——C#中如何使用R语言setwd()函数
在R语言编译器中,设置当前工作文件夹可以用setwd()函数. > setwd("e://桌面//")> setwd("e:\桌面\")> s ...
- R语言学习笔记-单一决策树
决策树比较简单明晰,但存在不稳定的风险,数据的微小变化会导致最佳决策树结构的巨大变化,且决策树可能会变得比较复杂. 其算法原理参见https://zhuanlan.zhihu.com/p/148010 ...
随机推荐
- angularJS 传参的四种方法
AngularJS - Passing data between pages 著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.作者:Ye Huang链接:https://www.z ...
- 手把手带你阅读Mybatis源码(二)执行篇
前言 上一篇文章提到了MyBatis是如何构建配置类的,也说了MyBatis在运行过程中主要分为两个阶段,第一是构建,第二就是执行,所以这篇文章会带大家来了解一下MyBatis是如何从构建完毕,到执行 ...
- vue 过渡 & 动画
过渡 & 动画 过渡动画 用css先定义好动画效果 .a-enter-active, .a-leave-active { transition: all 1.5s; } .a-enter, . ...
- python 解压、复制、删除 文件
一.python3解压文件 1.python 解压文件代码示例 如下代码主要实现zip.rar.tar.tar.gz四种格式的压缩文件的解压 def unzip_file(src_file, dst_ ...
- 计算机网络 From Mr.Liu
引言 本博客摘自Mr.Liu,原帖请点击这里. 感谢Mr.Liu,这个文章很充分的描述了计算机网络的核心知识点. 我还在学习中,所以没有进行自己的转述.图片因为是copy代码而没有获得,想看更详尽的, ...
- 基于已构建S2SH项目配置全注解方式简化配置文件
如果还不熟悉s2sh项目搭建的朋友可以先阅读 eclipse环境下基于tomcat-7.0.82构建struts2项目 eclipse环境下基于已构建struts2项目整合spring+hiberna ...
- NCE L3
单词 课文
- python基础入门之四 —— 列表
1.格式 [数据1,数据2,数据3,...] 列表可以一次性存多个数据,可以为不同的数据类型 2.下标 从0开始循序向下分配 3.常用函数 查找 index():返回指定数据所在位置下标,不存在就报错 ...
- css3新增边框、阴影、边框、背景、文本、字体
css3和css有什么区别?简单来讲css3是css(层叠样式表)技术的升级版本,css3新特征有很多,例如圆角效果.图形化边界.块阴影与文字阴影.使用RGBA实现透明效果.渐变效果.使用@Font- ...
- web渗透之XSS基本介绍
想学XSS必须得有基本得JS知识 JS基础BOM XSS漏洞原理 XSS(Cross Site Script),全称跨站脚本攻击.它指的是攻击者往web页面或者url里插入恶意JavaScript脚本 ...