Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >R4DS学习记录_ggplot2 - CG

R4DS学习记录_ggplot2 - CG

原创
作者头像
Crazy_George
发布于 2024-03-30 08:50:19
发布于 2024-03-30 08:50:19
2920
举报
文章被收录于专栏:R语言R语言一周生信入门

1. 数据和作图要求

描绘出企鹅不同族群的脚蹼长度和身体重量之间的关系,复现下图

本文目的复现此图
本文目的复现此图

2. 基本概念

2.1 变量-variable

A variable is a quantity, quality, or property that you can measure.

2.2 值-value

A value is the state of a variable when you measure it. The value of a variable may change from measurement to measurement.

2.3 observation

An observation is a set of measurements made under similar conditions (you usually make all of the measurements in an observation at the same time and on the same object). An observation will contain several values, each associated with a different variable. We’ll sometimes refer to an observation as a data point.

2.4 Tabular data

Tabular data is a set of values, each associated with a variable and an observation. Tabular data is tidy if each value is placed in its own “cell”, each variable in its own column, and each observation in its own row.

3. 准备工作

代码语言:r
AI代码解释
复制
install.packages("tidyverse")
library(tidyverse)
library(palmerpenguins)#包含penguins数据框
library(ggthemes)#包含colorblind safe color palette功能,ggplot2作图时需要。

4. 复现过程

4.1 查看penguins

代码语言:r
AI代码解释
复制
> penguins#查看penguins数据信息。或运行view(penguins)/glimpse()命令。
## A tibble: 344 × 8
#  species island    bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex    year
#   <fct>   <fct>              <dbl>         <dbl>             <int>       <int> <fct> <int>
# 1 Adelie  Torgersen           39.1          18.7               181        3750 male   2007
# 2 Adelie  Torgersen           39.5          17.4               186        3800 fema…  2007
# 3 Adelie  Torgersen           40.3          18                 195        3250 fema…  2007
# 4 Adelie  Torgersen           NA            NA                  NA          NA NA     2007
# 5 Adelie  Torgersen           36.7          19.3               193        3450 fema…  2007
# 6 Adelie  Torgersen           39.3          20.6               190        3650 male   2007
# 7 Adelie  Torgersen           38.9          17.8               181        3625 fema…  2007
# 8 Adelie  Torgersen           39.2          19.6               195        4675 male   2007
# 9 Adelie  Torgersen           34.1          18.1               193        3475 NA     2007
#10 Adelie  Torgersen           42            20.2               190        4250 NA     2007
## ℹ 334 more rows
## ℹ Use `print(n = ...)` to see more rows

本次作图的变量是:

  • species
  • flipper_length_mm
  • body_mass_g

4.2 作图逻辑

4.2.1. 定义横纵坐标

代码语言:r
AI代码解释
复制
ggolot(data = penguins)#此时是空白画板,没有定义作图
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
)#此时作图定义了横纵坐标,在ggplt2 中,The mapping argument is always defined in the aes() function

4.2.2 增加定义geom

ggplot2中有函数geom_bar()/geom_line()/ geom_point() / geom_boxplot()等。

代码语言:r
AI代码解释
复制
> ggplot(
+   data = penguins,
+   mapping = aes(x = flipper_length_mm, y = body_mass_g)
+ ) +
+   geom_point()
#Warning message:
#Removed 2 rows containing missing values or values outside the scale range
#(`geom_point()`). 
根据目的选择点图
根据目的选择点图

4.2.3 怎么区分族群?

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)
) +
  geom_point()
颜色区分族群
颜色区分族群

4.2.4 添加趋势线(新的几何对象)

geom_smmoth()

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)
) +
  geom_point() +
  geom_smooth(method = "lm")#draw the line of best fit based on a linear model with method = "lm"

4.2.5不同族群如何共享同一趋势线

理解ggplot2作图整体和局部的概念和区分

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(mapping = aes(color = species)) +
  geom_smooth(method = "lm")

4.2.6 根据不同族群将点分成不同形状

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(mapping = aes(color = species, shape = species)) +
  geom_smooth(method = "lm")

4.2.7 优化作图(标题/坐标标题等)

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(aes(color = species, shape = species)) +
  geom_smooth(method = "lm") +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
    x = "Flipper length (mm)", y = "Body mass (g)",
    color = "Species", shape = "Species"
  ) +
  scale_color_colorblind()

scale_color_colorblind(): improve the color palette to be colorblind safe

labs(): 各种title命名。

作图复现完成

5. 作业

5.1 How many rows are in penguins? How many columns?

代码语言:r
AI代码解释
复制
> glimpse(penguins)
#Rows: 344
#Columns: 8

5.2 What does the bill_depth_mm variable in the penguins data frame describe? Read the help for ?penguins to find out.

5.3 Make a scatterplot of bill_depth_mm vs. bill_length_mm. That is, make a scatterplot with bill_depth_mm on the y-axis and bill_length_mm on the x-axis. Describe the relationship between these two variables.What happens if you make a scatterplot of species vs. bill_depth_mm? What might be a better choice of geom?

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = bill_length_mm,y = bill_depth_mm,color = species,shape = species)
  )+
  geom_point()+
  geom_smooth(method = "lm")

可以看到三个不同的种群的趋势是相同的bill_length_mm越大,bill_depth_mm越大。但是如果把他们当作整体画趋势线就会的出错误的结果。

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = bill_length_mm,y = bill_depth_mm)
  )+
  geom_point(aes(color = species,shape = species))+
  geom_smooth(method = "lm")##错误方式
  
错误方式作图
错误方式作图

5.4 报错解决

代码语言:r
AI代码解释
复制
> ggplot(data = penguins) + 
+   geom_point()
#Error in `geom_point()`:
#! Problem while setting up geom.
#ℹ Error occurred in the 1st layer.
#Caused by error in `compute_geom_1()`:
#! `geom_point()` requires the following missing aesthetics: x and y.
#Run `rlang::last_trace()` to see where the error occurred.

5.5 What does the na.rm argument do in geom_point()? What is the default value of the argument? Create a scatterplot where you successfully use this argument set to TRUE.

运行?geom_point()

理解下边两段代码区别:

代码语言:r
AI代码解释
复制
> ggplot(
+   data = penguins,
+   mapping = aes(x = bill_length_mm,y = bill_depth_mm,color = species,shape = species)
+ )+
+   geom_point()+
+   geom_smooth(method = "lm")
#`geom_smooth()` using formula = 'y ~ x'
#Warning messages:
#1: Removed 2 rows containing non-finite outside the scale range (`stat_smooth()`). 
#2: Removed 2 rows containing missing values or values outside the scale range
代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = bill_length_mm,y = bill_depth_mm,color = species,shape = species)
  )+
  geom_point(na.rm = TRUE)+
  geom_smooth(method = "lm")
#`geom_smooth()` using formula = 'y ~ x'
#Warning message:
#Removed 2 rows containing non-finite outside the scale range #(`stat_smooth()`). 

5.6 Add the following caption to the plot you made in the previous exercise: “Data come from the palmerpenguins package.” Hint: Take a look at the documentation for labs().

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = bill_length_mm,y = bill_depth_mm,color = species,shape = species)
)+
  geom_point(na.rm = TRUE)+
  geom_smooth(method = "lm")+
  labs(
    caption = "Data come from the palmerpenius package"
  )

5.7 Recreate the following visualization. What aesthetic should bill_depth_mm be mapped to? And should it be mapped at the global level or at the geom level?

代码语言:r
AI代码解释
复制
> ggplot(
+   data = penguins,
+   mapping = aes(x = flipper_length_mm,y = body_mass_g)
+ )+
+   geom_point(aes(color = bill_depth_mm))+
+   geom_smooth()

5.8 Run this code in your head and predict what the output will look like. Then, run the code in R and check your predictions.

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g, color = island)
) +
  geom_point() +
  geom_smooth(se = FALSE)

5.9

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point() +
  geom_smooth()
代码语言:r
AI代码解释
复制
ggplot() +
  geom_point(
    data = penguins,
    mapping = aes(x = flipper_length_mm, y = body_mass_g)
  ) +
  geom_smooth(
    data = penguins,
    mapping = aes(x = flipper_length_mm, y = body_mass_g)
  )

以上两行代码运行结果的图一致。

#6 代码写法

代码语言:r
AI代码解释
复制
ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point()
代码语言:r
AI代码解释
复制
ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) + 
  geom_point()
代码语言:r
AI代码解释
复制
penguins |> 
  ggplot(aes(x = flipper_length_mm, y = body_mass_g)) + 
  geom_point()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
ggplot2绘制散点图配合拟合曲线和边际分布直方图
stat_poly_line 是一个在 ggplot2 图形中添加多项式回归线的函数。这个函数直接计算多项式回归模型,并将拟合线添加到图形上。它允许指定多项式的阶数,即回归方程中最高次项的次数。可直接在图形上添加拟合线,而不是基于数据点的平滑。
R语言数据分析指南
2023/11/03
2.3K0
ggplot2绘制散点图配合拟合曲线和边际分布直方图
ggdensity:更直观的密度估计图形
ggdensity是一个新的ggplot2扩展包,用于展示二维密度估计,使用的方法是基于最高密度区域(HDR)的密度估计方法。(什么是HDR?简单的说就是在指定概率所覆盖的样本空间所有可能的区域中,HDR具有可能的最小区域。)
自学气象人
2023/06/20
1.1K0
ggdensity:更直观的密度估计图形
ggplot2绘制散点图:进阶可视化技巧
R语言数据分析指南
2024/05/17
2150
ggplot2绘制散点图:进阶可视化技巧
R4DS-学习记录-ggplot2_2-CG
A variable is numerical (or quantitative) if it can take on a wide range of numerical values,visualization for distributions of continuous variables is a histogram.
Crazy_George
2024/04/01
1420
利用小提琴图探索帕尔默企鹅数据
众所周知,可视化好不好看,全凭注释是否精(花)准(哨)。接下来就是最考验技术的地方了!
HsuHeinrich
2025/04/23
690
利用小提琴图探索帕尔默企鹅数据
利用散点图探索帕尔默企鹅数据
参考:Scatterplot with labels and text repel in Matplotlib[1]
HsuHeinrich
2025/04/29
590
利用散点图探索帕尔默企鹅数据
R语言机器学习caret-09:决策树的小例子
今天给大家演示下caret做决策树的例子,但其实并不是很好用,还不如之前介绍的直接使用rpart,或者tidymodels,mlr3。
医学和生信笔记
2023/08/30
3130
R语言机器学习caret-09:决策树的小例子
(数据科学学习手札97)掌握pandas中的transform
  开门见山,在pandas中,transform是一类非常实用的方法,通过它我们可以很方便地将某个或某些函数处理过程(非聚合)作用在传入数据的每一列上,从而返回与输入数据形状一致的运算结果。
Feffery
2020/10/26
1.3K0
(数据科学学习手札97)掌握pandas中的transform
Python-seaborn 基础图表绘制-散点图
上期推文推出第一篇基础图表绘制-R-ggplot2 基础图表绘制-散点图 的绘制推文,得到了很多小伙伴的喜欢,也是我更加想使这个系列做的更加完善和系统,我之前也有说过,会推出Python和R的两个版本绘制教程,接下来我们就推出基础散点图的Python绘制版本。本期主要涉及的知识点如下:
数据森麟
2020/11/23
1.6K0
Python-seaborn 基础图表绘制-散点图
day4 呦呦鹿鸣——R for data science阅读笔记之ggplot()
https://r4ds.hadley.nz/data-visualize#visualizing-relationships
用户10918035
2024/01/19
5280
day5记录 R语言绘图
#此处如果写color = "xxx" 结果是只会出来一种颜色,因为会认为只需要一种颜色
Qianhui Cheng
2025/02/11
1050
从零开始的异世界生信学习 R语言部分 05 作图-1
ggplot2的特殊语法规则:列名不带引号,行末写加号(加号表示不同函数之间的连接)
用户10361520
2023/03/05
8290
R语言day6:从此用ggplot函数画好看的图
不会写代码的医学生
2024/03/12
2770
monochromeR:一种创建单色调色板的简单方法
R语言数据分析指南
2023/08/18
2850
monochromeR:一种创建单色调色板的简单方法
R绘图——ggplot2
ggplot2默认没有引号,第一行为全局设置,以下分别为分图层。全局设置后一定要由+,每个分图层可以单独设置映射aes
用户10803004
2023/10/31
3210
数据可视化 | seaborn绘制散点图
由于涉及的图表类型为多类别散点图的绘制,在使用常规matplotlib进行绘制时会显得格外繁琐,所以我们选择了对matplotlib进行了更高级的API封装,使作图更加容易的seaborn包进行图表的绘制,更多seaborn 介绍,大家可以直接去seaborn官网进行相关资料的查阅。数据的读取使用的功能强大的数据处理包 pandas ,这里只是进行简单的删除空值操作,直接使用dropna() 函数操作即可,我们直接预览数据,如下(部分):
郭好奇同学
2020/11/25
2K0
数据可视化 | seaborn绘制散点图
ggplot2绘图(R_03)
画图的思维:1.我的数据适合什么样的图?2.搜画图代码 3.仿制示例数据 4.套代码,调细节
用户10803254
2023/10/23
3060
seaborn从入门到精通03-绘图功能实现03-分布绘图distributional plots
本文主要是seaborn从入门到精通系列第3篇,本文介绍了seaborn的绘图功能实现,本文是分布绘图,同时介绍了较好的参考文档置于博客前面,读者可以重点查看参考链接。本系列的目的是可以完整的完成seaborn从入门到精通。重点参考连接
IT从业者张某某
2023/10/16
3940
seaborn从入门到精通03-绘图功能实现03-分布绘图distributional plots
技能树Day03_直播课05-06_R作图与综合利用
属性设置:映射:根据数据的某一列的内容分配颜色;统一设置:把图形设置为一个颜色,与数据无关
sheldor没耳朵
2024/07/19
1380
技能树Day03_直播课05-06_R作图与综合利用
R-ggplot2 基础图表绘制-散点图
本期开始陆续推出基础图表的绘制推文教程,也算是自己的一个基础知识积累和巩固,希望和大家一同学习进步。这期的推文是关于散点图的绘制,主要知识点如下:
DataCharm
2021/02/22
1.3K0
R-ggplot2 基础图表绘制-散点图
相关推荐
ggplot2绘制散点图配合拟合曲线和边际分布直方图
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档