可视化谷物产量

R 函数编写入门

Richie Cotton

Data Evangelist at DataCamp

玉米数据集

glimpse(corn)
Observations: 6,381
Variables: 6
$ year                   <int> 1866, 1866, 1866, 1866, 1866, 1866...
$ state                  <chr> "Alabama", "Arkansas", "California...
$ farmed_area_acres      <dbl> 1050000, 280000, 42000, 57000, 200...
$ yield_bushels_per_acre <dbl> 9.0, 18.0, 28.0, 34.0, 23.0, 9.0, ...
$ farmed_area_ha         <dbl> 424919.92, 113311.98, 16996.80, 23...
$ yield_kg_per_ha        <dbl> 79.29892, 158.59784, 246.70776, 29...
R 函数编写入门

ggplot2:绘制多条线

ggplot(dataset, aes(x, y)) +
  geom_line(aes(group = group))

一幅多条折线的图。数据是示例,但重点是:线条按数据框中的 group 列分组。

R 函数编写入门

ggplot2:平滑趋势

ggplot(dataset, aes(x, y)) +
  geom_line(aes(group = group)) +
  geom_smooth()

与上一页相同的折线图,但新增一条平滑趋势线。该线未分组,因为分组美学只用于线图层,而非整个图。很巧妙。

R 函数编写入门

ggplot2:分面

ggplot(dataset, aes(x, y)) +
  geom_line(aes(group = group)) +
  geom_smooth() +
  facet_wrap(vars(facet))

与上次相同的图,但现在因 facet_wrap 调用而分为四个小面板,标记为 A 到 D。

R 函数编写入门

美国人口普查分区

这是一个 statebin 图:每个美国州用一个方块表示,方块按行列排列,整体近似美国地图形状。各人口普查分区用不同颜色表示。

R 函数编写入门

dplyr 内连接

dataset1 %>%
  inner_join(dataset2, by = "column_to_join_on")
R 函数编写入门

开始练习!

R 函数编写入门

Preparing Video For Download...