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

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

library(tidyverse)

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

7.2.7 练习题

============

1.钻石数据集分面


  • 切工分面,克拉数分组
ggplot(diamonds, aes(price, fill = clarity)) + geom_histogram() + 
    facet_wrap(~cut)

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第七章_第1张图片
image.png
  • 克拉数分面,切工分组
ggplot(diamonds, aes(price, fill = cut)) + geom_histogram() + 
    facet_wrap(~clarity)

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

颜色分组如果太多的话,会看不清楚,所以其实还是颜色分组少一点儿的好一些

2.颜色当中价格和克拉的关系


如果使用分组比较的话

ggplot(diamonds, aes(carat, price, color = color)) + geom_point() + 
    geom_smooth()

## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第七章_第3张图片
image.png

由于数据量较大,分组的话,看不出数据分布的情况。如果使用分面则可以

ggplot(diamonds, aes(carat, price)) + geom_point() + 
    geom_smooth() + facet_wrap(~color)

## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
[R|ggplot2] ggplot2数据分析与图形艺术课后题:第七章_第4张图片
image.png

3.facet_wrap和facet_grid的比较


从文档中读取:facet_wrap将一维面板序列包装成二维。通常,与facet_grid相比,这是对屏幕空间的更好利用,因为大多数显示器都是大致矩形的。

4. 重复下面的图形


mpg2 <- subset(mpg, cyl != 5 & drv %in% c("4", "f") & class != "2seater")
head(mpg2)

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

ggplot(mpg2, aes(displ, hwy)) + geom_point() + 
    geom_smooth(data = select(mpg2, -class),se = F) + 
    facet_wrap(~class)

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

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