[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章

这个主要是对《ggplot2数据分析与图形艺术》第二章相关练习题的总

ggplot2数据分析与图形艺术课后题:第二章
ggplot2数据分析与图形艺术课后题:第三章
ggplot2数据分析与图形艺术课后题:第五章
ggplot2数据分析与图形艺术课后题:第六章
ggplot2数据分析与图形艺术课后题:第七章
ggplot2数据分析与图形艺术课后题:第八章

  • 2.2.1 耗油量数据
    • 1. 列举5个获取mpg数据的函数
    • 2. 如何获取ggplot2的内置其他数据集
    • 3. 如何将cty和hwy转换为欧盟标准的每百千米油耗
    • 4.数据集的分析
  • 2.3 知识要点
    • 如何描述cty和hwy的关系
    • 2 某一个图形展示的信息内容
  • 2.4 颜色,大小,形状和其他标度
    • 1-2.
      对于颜色、形状和大小的映射,在连续性变量和分类变量之间吗的区别
    • 3.
      drv和cty是什么关系?displ和class以及drv的区别
  • 2.5 分面
    • 1. 分面映射到连续性变量会怎么样
    • 4. scale参数的含义
  • 2.6 几何对象
    • 1. 下面图形有什么问题,如果进行修改
    • 2. reorder的作用
    • 3.探索直方图的分布的间距
    • 4.探索价格和切工的关系
    • 5. weight的作用
    • 6. 二维的分类数据可视化
    library(tidyverse)

2.2.1 耗油量数据

  1. 列举5个获取mpg数据的函数

对于一个数据集而言,我们在获得数据集之后都要查看数据集的集合。一般而言需要查看

1.1 查看数据的部分数据是说明

### 查看数据的前几行
head(mpg)

## # A tibble: 6 x 11
##   manufacturer model displ  year   cyl trans  drv     cty   hwy fl    class
##                     
## 1 audi         a4      1.8  1999     4 auto(… f        18    29 p     comp…
## 2 audi         a4      1.8  1999     4 manua… f        21    29 p     comp…
## 3 audi         a4      2    2008     4 manua… f        20    31 p     comp…
## 4 audi         a4      2    2008     4 auto(… f        21    30 p     comp…
## 5 audi         a4      2.8  1999     6 auto(… f        16    26 p     comp…
## 6 audi         a4      2.8  1999     6 manua… f        18    26 p     comp…

### 查看数据的最后几行
tail(mpg)

## # A tibble: 6 x 11
##   manufacturer model  displ  year   cyl trans drv     cty   hwy fl    class
##                     
## 1 volkswagen   passat   1.8  1999     4 auto… f        18    29 p     mids…
## 2 volkswagen   passat   2    2008     4 auto… f        19    28 p     mids…
## 3 volkswagen   passat   2    2008     4 manu… f        21    29 p     mids…
## 4 volkswagen   passat   2.8  1999     6 auto… f        16    26 p     mids…
## 5 volkswagen   passat   2.8  1999     6 manu… f        18    26 p     mids…
## 6 volkswagen   passat   3.6  2008     6 auto… f        17    26 p     mids…

1.2 数据各行的信息是什么。

str(mpg)

## Classes 'tbl_df', 'tbl' and 'data.frame':    234 obs. of  11 variables:
##  $ manufacturer: chr  "audi" "audi" "audi" "audi" ...
##  $ model       : chr  "a4" "a4" "a4" "a4" ...
##  $ displ       : num  1.8 1.8 2 2 2.8 2.8 3.1 1.8 1.8 2 ...
##  $ year        : int  1999 1999 2008 2008 1999 1999 2008 1999 1999 2008 ...
##  $ cyl         : int  4 4 4 4 6 6 6 4 4 4 ...
##  $ trans       : chr  "auto(l5)" "manual(m5)" "manual(m6)" "auto(av)" ...
##  $ drv         : chr  "f" "f" "f" "f" ...
##  $ cty         : int  18 21 20 21 16 18 18 18 16 20 ...
##  $ hwy         : int  29 29 31 30 26 26 27 26 25 28 ...
##  $ fl          : chr  "p" "p" "p" "p" ...
##  $ class       : chr  "compact" "compact" "compact" "compact" ...

glimpse(mpg)

## Observations: 234
## Variables: 11
## $ manufacturer  "audi", "audi", "audi", "audi", "audi", "audi", "au…
## $ model         "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quatt…
## $ displ         1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2…
## $ year          1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 199…
## $ cyl           4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, …
## $ trans         "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)",…
## $ drv           "f", "f", "f", "f", "f", "f", "f", "4", "4", "4", "…
## $ cty           18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17,…
## $ hwy           29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25,…
## $ fl            "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "…
## $ class         "compact", "compact", "compact", "compact", "compac…

对于strglimpse而言。glimpse会比str多显示数据的数据量

1.3 查看数据的纬度

### 整体查看数据的行数和列数
dim(mpg)

## [1] 234  11

### 单独查看
nrow(mpg)

## [1] 234

ncol(mpg)

## [1] 11

1.4 有时候我们只想要查看数据的列名或者行名

### 查看列名
names(mpg)

##  [1] "manufacturer" "model"        "displ"        "year"        
##  [5] "cyl"          "trans"        "drv"          "cty"         
##  [9] "hwy"          "fl"           "class"

colnames(mpg) ## 两者在数据框里面是等价的。

##  [1] "manufacturer" "model"        "displ"        "year"        
##  [5] "cyl"          "trans"        "drv"          "cty"         
##  [9] "hwy"          "fl"           "class"

namescolnames在数据框当中是等价了。但是names的范围更广,对于有名字的list或者vector都可以使用。而colnames则不行

### 查看行名
rownames(mpg)

##   [1] "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"   "9"   "10"  "11" 
##  [12] "12"  "13"  "14"  "15"  "16"  "17"  "18"  "19"  "20"  "21"  "22" 
##  [23] "23"  "24"  "25"  "26"  "27"  "28"  "29"  "30"  "31"  "32"  "33" 
##  [34] "34"  "35"  "36"  "37"  "38"  "39"  "40"  "41"  "42"  "43"  "44" 
##  [45] "45"  "46"  "47"  "48"  "49"  "50"  "51"  "52"  "53"  "54"  "55" 
##  [56] "56"  "57"  "58"  "59"  "60"  "61"  "62"  "63"  "64"  "65"  "66" 
##  [67] "67"  "68"  "69"  "70"  "71"  "72"  "73"  "74"  "75"  "76"  "77" 
##  [78] "78"  "79"  "80"  "81"  "82"  "83"  "84"  "85"  "86"  "87"  "88" 
##  [89] "89"  "90"  "91"  "92"  "93"  "94"  "95"  "96"  "97"  "98"  "99" 
## [100] "100" "101" "102" "103" "104" "105" "106" "107" "108" "109" "110"
## [111] "111" "112" "113" "114" "115" "116" "117" "118" "119" "120" "121"
## [122] "122" "123" "124" "125" "126" "127" "128" "129" "130" "131" "132"
## [133] "133" "134" "135" "136" "137" "138" "139" "140" "141" "142" "143"
## [144] "144" "145" "146" "147" "148" "149" "150" "151" "152" "153" "154"
## [155] "155" "156" "157" "158" "159" "160" "161" "162" "163" "164" "165"
## [166] "166" "167" "168" "169" "170" "171" "172" "173" "174" "175" "176"
## [177] "177" "178" "179" "180" "181" "182" "183" "184" "185" "186" "187"
## [188] "188" "189" "190" "191" "192" "193" "194" "195" "196" "197" "198"
## [199] "199" "200" "201" "202" "203" "204" "205" "206" "207" "208" "209"
## [210] "210" "211" "212" "213" "214" "215" "216" "217" "218" "219" "220"
## [221] "221" "222" "223" "224" "225" "226" "227" "228" "229" "230" "231"
## [232] "232" "233" "234"
  1. 如何获取ggplot2的内置其他数据集

在一个R包里面。设计者通常为了进行示例演示会放很多内置的数据集。如果我们知道数据集的名字,可以通过data来获得。假如我们想要获得ggplot2里面的diamonds数据集

library(ggplot2)
data("diamonds")

如果我们想要知道这个包里面有那些数据集,我们同样也可以通过data来实现

data(package = "ggplot2")

如果我们想要获得内置数据集的更多信息,我们可以通过vcdExtra包当中的datasets来查看

vcdExtra::datasets("ggplot2")

##              Item      class      dim
## 1        diamonds data.frame 53940x10
## 2       economics data.frame    574x6
## 3  economics_long data.frame   2870x4
## 4       faithfuld data.frame   5625x3
## 5     luv_colours data.frame    657x4
## 6         midwest data.frame   437x28
## 7             mpg data.frame   234x11
## 8          msleep data.frame    83x11
## 9    presidential data.frame     11x4
## 10          seals data.frame   1155x4
## 11      txhousing data.frame   8602x9
##                                                                Title
## 1                                Prices of 50,000 round cut diamonds
## 2                                            US economic time series
## 3                                            US economic time series
## 4                           2d density estimate of Old Faithful data
## 5                                            'colors()' in Luv space
## 6                                               Midwest demographics
## 7  Fuel economy data from 1999 and 2008 for 38 popular models of car
## 8       An updated and expanded version of the mammals sleep dataset
## 9                    Terms of 11 presidents from Eisenhower to Obama
## 10                                    Vector field of seal movements
## 11                                               Housing sales in TX
  1. 如何将cty和hwy转换为欧盟标准的每百千米油耗

对于数据的转换,我们可以通过dplyr包的mutate来实现

mpg %>%
  mutate(cty_l100km = cty * 235.215,
         hwy_l100lm = hwy * 235.215) %>% head()

## # A tibble: 6 x 13
##   manufacturer model displ  year   cyl trans drv     cty   hwy fl    class
##                    
## 1 audi         a4      1.8  1999     4 auto… f        18    29 p     comp…
## 2 audi         a4      1.8  1999     4 manu… f        21    29 p     comp…
## 3 audi         a4      2    2008     4 manu… f        20    31 p     comp…
## 4 audi         a4      2    2008     4 auto… f        21    30 p     comp…
## 5 audi         a4      2.8  1999     6 auto… f        16    26 p     comp…
## 6 audi         a4      2.8  1999     6 manu… f        18    26 p     comp…
## # … with 2 more variables: cty_l100km , hwy_l100lm 

4.数据集的分析

  1. 哪个制造商有最多的车型

对于一个分类变量的个数的统计,R当中有一个简单的函数可以来进行操作table。我们可以使用table来进行操作进一步来进行排序。同样的也是可以通过dplyr来进行操作的

### 方法1:
table(mpg$manufacturer) %>% sort(decreasing = T)

## 
##      dodge     toyota volkswagen       ford  chevrolet       audi 
##         37         34         27         25         19         18 
##    hyundai     subaru     nissan      honda       jeep    pontiac 
##         14         14         13          9          8          5 
## land rover    mercury    lincoln 
##          4          4          3

### 方法2:
mpg %>% count(manufacturer, sort = T)

## # A tibble: 15 x 2
##    manufacturer     n
##            
##  1 dodge           37
##  2 toyota          34
##  3 volkswagen      27
##  4 ford            25
##  5 chevrolet       19
##  6 audi            18
##  7 hyundai         14
##  8 subaru          14
##  9 nissan          13
## 10 honda            9
## 11 jeep             8
## 12 pontiac          5
## 13 land rover       4
## 14 mercury          4
## 15 lincoln          3

我们发现Dodge拥有最多的车型

  1. 哪个车型的型号最丰富

这个和之前的一样,只是说对model变量来进行基数

mpg %>% count(model, sort = T)

## # A tibble: 38 x 2
##    model                   n
##                   
##  1 caravan 2wd            11
##  2 ram 1500 pickup 4wd    10
##  3 civic                   9
##  4 dakota pickup 4wd       9
##  5 jetta                   9
##  6 mustang                 9
##  7 a4 quattro              8
##  8 grand cherokee 4wd      8
##  9 impreza awd             8
## 10 a4                      7
## # … with 28 more rows

最多型号的车型是caravan 2wd

  1. 如果删除驱动系统
str_replace_all(mpg$model, c("quattro" = "", "4wd" = "",
                                              "2wd" = "", "awd" = "")) %>% str_trim() %>% table() %>% sort(decreasing = T)

## .
##                 a4            caravan    ram 1500 pickup 
##                 15                 11                 10 
##              civic      dakota pickup              jetta 
##                  9                  9                  9 
##            mustang     grand cherokee            impreza 
##                  9                  8                  8 
##              camry       camry solara            durango 
##                  7                  7                  7 
##        f150 pickup             passat             sonata 
##                  7                  7                  7 
##            tiburon      toyota tacoma            4runner 
##                  7                  7                  6 
##             altima           explorer           forester 
##                  6                  6                  6 
##         new beetle     c1500 suburban            corolla 
##                  6                  5                  5 
##           corvette         grand prix                gti 
##                  5                  5                  5 
##             malibu        k1500 tahoe        mountaineer 
##                  5                  4                  4 
##         pathfinder        range rover                 a6 
##                  4                  4                  3 
##         expedition             maxima          navigator 
##                  3                  3                  3 
## land cruiser wagon 
##                  2

如果删除驱动系统。则最多的车型是a4

2.3 知识要点

如何描述cty和hwy的关系

首先我们来查看数据类型

mpg[c("cty", "hwy")]

## # A tibble: 234 x 2
##      cty   hwy
##     
##  1    18    29
##  2    21    29
##  3    20    31
##  4    21    30
##  5    16    26
##  6    18    26
##  7    18    27
##  8    18    26
##  9    16    25
## 10    20    28
## # … with 224 more rows

这两个都是连续性变量。如果要看两个连续性变量之间的关系的话,最常用的是对两者进行相关分析。在不考虑相关分析的实行条件下。我们来进行简单的相关分析

cor(mpg$cty, mpg$hwy)

## [1] 0.9559159

通过相关系数我们可以看到,两者存在强烈的正相关。如果通过图形的话。则是

ggplot(mpg, aes(cty, hwy)) + geom_point() + geom_smooth()

## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第1张图片
image.png

2 某一个图形展示的信息内容

这个图形是

ggplot(mpg, aes(model, manufacturer)) + geom_point()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第2张图片
image.png

抛开可视化的问题不谈。图片主要是展示两个分类变量值之间的关系。且每两个变量只有一个数据点,所以其实不适合用图形展示的要么就是展示其中一个的个数统计,使用另外一个来配色区分。

2.4 颜色,大小,形状和其他标度

1-2. 对于颜色、形状和大小的映射,在连续性变量和分类变量之间吗的区别

颜色和大小而言,连续性和分类变量都可以来进行映射。而对于shape变量。只能映射分类变量。因为点的形状只有集中。不能随着数字的变化而变化。如果映射到连续性变量上了,则会发生错误。

ggplot(mpg, aes(cty, hwy, shape = trans)) +
  geom_point()

## Warning: The shape palette can deal with a maximum of 6 discrete values
## because more than 6 becomes difficult to discriminate; you have
## 10. Consider specifying shapes manually if you must have them.

## Warning: Removed 96 rows containing missing values (geom_point).
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第3张图片
image.png
  1. drv和cty是什么关系?displ和class以及drv的区别

查看drvcty的数据类型。其中drv分类变量,cty是连续性变量。对于连续性变量和分类变量的可视化,最常用的是箱式图来进行可视化。

ggplot(mpg, aes(drv, cty)) + geom_boxplot()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第4张图片
image.png

displ是一个连续性变量,classdrv是两个分类变量。一个连续性变量和两个分类变量数据的可视化。一般是可视化一个连续性变量和分类变量,同时把另外一个变量映射到另外一个参数上(颜色,形状等等)。或者使用另外一个变量进行分面也可以。

### 映射到另外一个参数上
ggplot(mpg,aes(class, displ, fill = drv)) + geom_boxplot()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第5张图片
image.png
### 分面
ggplot(mpg, aes(class ,displ)) + geom_boxplot() + facet_grid(~drv)
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第6张图片
image.png

2.5 分面

  1. 分面映射到连续性变量会怎么样

如果分面映射到连续性变量,这个不会不出图。也会对所有的分类进行分面可视化,但是这样的结果对于数据的分析而言没有任何意义

  1. scale参数的含义

对于facet_grid当中的scale参数。其接受洗个参数:fixed(默认);
free_x;
free_y以及free。其含义是对于分面的坐标轴是否都采取一样的范围还是每个分面采取不同的范围。默认的是采取一样的范围

mpg1 <- mpg[mpg$cyl %in% c(4,8),]

p1 <- ggplot(mpg1, aes(displ, cty)) +
    geom_point() +
    facet_wrap(~ cyl, scales = "fixed") + 
    ggtitle("fixed")
p2 <- ggplot(mpg1, aes(displ, cty)) +
    geom_point() +
    facet_wrap(~ cyl, scales = "free_y") + 
    ggtitle("free_y")
p3 <- ggplot(mpg1, aes(displ, cty)) +
    geom_point() +
    facet_wrap(~ cyl, scales = "free_x") +
    ggtitle("free_x")
p4 <- ggplot(mpg1, aes(displ, cty)) +
    geom_point() +
    facet_wrap(~ cyl, scales = "free") + 
    ggtitle("free")
cowplot::plot_grid(p1, p2, p3, p4, ncol = 2)
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第7张图片
image.png

2.6 几何对象

  1. 下面图形有什么问题,如果进行修改

ggplot(mpg, aes(cty, hwy)) + geom_point()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第8张图片
image.png

上面的图形,很多点都重叠到一起了,为了可视化更好一些,需要对重叠的点进行抖动出来

ggplot(mpg, aes(cty, hwy)) + geom_jitter()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第9张图片
image.png
  1. reorder的作用

坐标轴对于字符型变量在进行绘图的时候会转换我因子来进行排序,默认的因子的顺序是基于字母顺序来的
分类变量或者因子变量的排序是基于字母顺序或者因子水平来进行排序的。所以在默认的图形当中其X轴是按照字母顺序来进行排序的

levels(as.factor(mpg$class))

## [1] "2seater"    "compact"    "midsize"    "minivan"    "pickup"    
## [6] "subcompact" "suv"

ggplot(mpg, aes(class, hwy)) + geom_boxplot()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第10张图片
image.png

这样的结果不是很美观,如果箱式图可以按照从低到高或者从高到底的顺序来排序就更加美观了。
reorder函数是基于基于某一个变量的一个统计量来对目标因子的水平。默认的是基于另外一个变量的均值来进行排序的。所以这样修改完之后,X轴的因子水平就会按照其均值的大小来进行排序,这样可视化的结果就更加的好看了

ggplot(mpg, aes(reorder(class, hwy), hwy)) + geom_boxplot()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第11张图片
image.png

3.探索直方图的分布的间距

直方图分布的间距可以通过binwidth来进行调整。默认的是分成30组。具体是否合适需要自己来调整

ggplot(diamonds, aes(carat)) + geom_histogram(binwidth = 0.02)
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第12张图片
image.png

4.探索价格和切工的关系

从分布的角度而言的话,我们可以通过可视化的角度来查看各个切工之间其基本的分布是什么样子的

ggplot(diamonds, aes(price, color = cut)) + geom_freqpoly()

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第13张图片
image.png

通过图形我们可以看到除了Very Good组和Premium组之间分布类似之外,其他各个组都是存在明显的分布差异的。但是这个只是从可视化的角度看到的。具体的是不是真的有差异,只能通过统计来进行分析了

对于探讨各组之间是否存在差异而言。就统计角度而言,如果我们要谈论多组之间的比较。可以进行方差分析(如果服从正太分布且方差齐的情况下)

fit <- aov(price ~ cut, data = diamonds)
summary(fit)

##                Df    Sum Sq   Mean Sq F value Pr(>F)    
## cut             4 1.104e+10 2.760e+09   175.7 <2e-16 ***
## Residuals   53935 8.474e+11 1.571e+07                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

我们可以看到。各组之间是存在差异的。进一步我们来进行各组之间的两两比较。如果要进行两两比较的话,因为有五组以上的分组,我们使用Turkey发来进行比较

posthoc <- TukeyHSD(x=fit, 'cut', conf.level=0.95)
posthoc

##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = price ~ cut, data = diamonds)
## 
## $cut
##                          diff         lwr        upr     p adj
## Good-Fair          -429.89331  -740.44880  -119.3378 0.0014980
## Very Good-Fair     -376.99787  -663.86215   -90.1336 0.0031094
## Premium-Fair        225.49994   -59.26664   510.2665 0.1950425
## Ideal-Fair         -901.21579 -1180.57139  -621.8602 0.0000000
## Very Good-Good       52.89544  -130.15186   235.9427 0.9341158
## Premium-Good        655.39325   475.65120   835.1353 0.0000000
## Ideal-Good         -471.32248  -642.36268  -300.2823 0.0000000
## Premium-Very Good   602.49781   467.76249   737.2331 0.0000000
## Ideal-Very Good    -524.21792  -647.10467  -401.3312 0.0000000
## Ideal-Premium     -1126.71573 -1244.62267 -1008.8088 0.0000000

通过结果我们可以发现,Premium-FairVery Good-Good在这两组之间比较的时候是没有差异的。反而两个分布类似的Premium-Good则存在差异。

  1. weight的作用

我们在评价一个数据的时候,有时候需要另外一个数据来进行加权后进行重新评价。这个时候就可以用到weight参数了。具体的可以参考3.9的解释。

  1. 二维的分类数据可视化

对于两个都是分类变量的可视化,基本上常用的就是来使用其中一个做柱状图然后另外一个来进行颜色的区分。

ggplot(mpg, aes(trans, fill = factor(cyl))) + geom_bar()
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第14张图片
image.png

我们可以通过改变position来可视化不同的方式

ggplot(mpg, aes(trans, fill = factor(cyl))) + geom_bar(position = "fill")
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第15张图片
image.png
ggplot(mpg, aes(trans, fill = factor(cyl))) + geom_bar(position = "dodge")
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章_第16张图片
image.png

这样的,我们可以使用棒棒糖图雷达图以及桑葚图等等来对数据的更好看的可视化。

你可能感兴趣的:([R|ggplot2] ggplot2数据分析与图形艺术课后题:第二章)