DataCamp课程 Chapter.2
2021-07-08 本文已影响0人
Jason数据分析生信教室
Tidyverse课程目录
Chapter 1. 数据整形
Chapter 2. 数据可视化
Chapter 3. 分组和概括
Chapter 4. 可视化类型
Chapter 2. 数据可视化
这一章里会用到ggplot2包来可视化数据。数据的话和Chapter一样,用到了gapminder里的数据。首先运行一下本次会用到的三个包。
ggplot2小试牛刀
ggplot2的名声估计大家也早有耳闻,在这里做简单的入门介绍。之后会出专题详细讲解,功能之强大罄竹难书(用词不当)。
# Load the ggplot2 package as well
library(gapminder)
library(dplyr)
library(ggplot2)
接下来选取数据gapminder里year为1952的数据。并定义为新的数据集名字叫gapminder_1952。
# Create gapminder_1952
gapminder_1952 <- gapminder %>%
filter(year==1952)
创建一个x轴是pop,y轴是gdpPercap的散点图。
# Change to put pop on the x-axis and gdpPercap on the y-axis
ggplot(gapminder_1952, aes(x = pop, y = gdpPercap)) +
geom_point()
继续创建一个x轴是pop,y轴是lifeExp的散点图。
坐标轴log处理
上面两张图看上去明显不顺眼,需要把x轴进行对数处理一下。方法有很多,在这里我们用ggplot2里的指令scale_x_log10()对坐标轴进行处理。
# Change this plot to put the x-axis on a log scale
ggplot(gapminder_1952, aes(x = pop, y = lifeExp)) +
geom_point() +
scale_x_log10()
同理,不只是x轴,y轴也可以通过这样的方式进行log转换。
# Scatter plot comparing pop and gdpPercap, with both axes on a log scale
ggplot(gapminder_1952, aes(x = pop, y = gdpPercap)) +
geom_point() +
scale_x_log10() +
scale_y_log10()
图形美化
x轴是pop,y轴是lifeExp,根据continent给数据上色,然后x轴进行log转变。
# Scatter plot comparing pop and lifeExp, with color representing continent
ggplot(gapminder_1952, aes(x = pop, y = lifeExp,color = continent)) +
geom_point() +
scale_x_log10()
不仅可以添加颜色属性,还可以添加大小属性,比方说在上图的基础上根据
gdpPercap设置点的大小。
# Add the size aesthetic to represent a country's gdpPercap
ggplot(gapminder_1952, aes(x = pop, y = lifeExp, color = continent,size=gdpPercap)) +
geom_point() +
scale_x_log10()
-总结一下,图形美化里用到的四个参数
| Aesthetics | Variable |
|---|---|
| x | pop |
| y | lifeExp |
| color | continent |
| size | gdpPercap |
图形分割
利用facet_wrap根据continent对图形进行分割。
# Scatter plot comparing pop and lifeExp, faceted by continent
ggplot(gapminder_1952, aes(x = pop, y = lifeExp))+
geom_point()+
scale_x_log10()+
facet_wrap(~ continent)
x是gdpPercap,y是lifeExp,color是continent, size是pop,最后根据year分割图形。
# Scatter plot comparing gdpPercap and lifeExp, with color representing continent
# and size representing population, faceted by year
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, color = continent,size=pop)) +
geom_point() +
scale_x_log10()+
facet_wrap(~year)