DataCamp课程 <Tidyverse> Chapter.4 可视化类型

本教程介绍了如何使用Tidyverse包进行数据整形、可视化和分析。通过`ggplot2`库,展示了如何创建线图、按年份和大陆分组的线图、棒状图、直方图以及箱线图,涵盖了数据的中位数计算、时间序列变化和分布展示。同时,涉及到数据过滤、分组、概括以及对数转换等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tidyverse课程目录

Chapter 1. 数据整形
Chapter 2. 数据可视化
Chapter 3. 分组和概括
Chapter 4. 可视化类型

Chapter.4 可视化类型

这一章节会结合到之前说到的语法和知识。介绍几种最基础和常用的ggplot的图形。

线图

首先根据year对数据进行组化,然后用summarize计算出dgpPercap的中位数命名为变量medianGdpPercap。最后对每年的medianGdpPercap进行可视化画出线图

library(gapminder)
library(dplyr)
library(ggplot2)

# Summarize the median gdpPercap by year, then save it as by_year
by_year<- gapminder %>% 
group_by(year)%>% 
summarize(medianGdpPercap=median(gdpPercap))


# Create a line plot showing the change in medianGdpPercap over time
ggplot(by_year,aes(x=year,y=medianGdpPercap))+
geom_line()+
expand_limits(y = 0)

接下来这个例子是根据两个变量yearcontinent对数据进行组化,求得gdpPercap的中位数,x轴为year,y轴为gdpPercap的中位数进行做图。并且根据continent进行上色。

# Summarize the median gdpPercap by year & continent, save as by_year_continent
by_year_continent<- gapminder %>% 
group_by(year,continent) %>% 
summarize(medianGdpPercap=median(gdpPercap))

# Create a line plot showing the change in medianGdpPercap by continent over time
ggplot(by_year_continent,aes(x=year,y=medianGdpPercap,color=continent))+
geom_line()+
expand_limits(y = 0)

棒状图

选取year1952的数据,然后根据continent进行组化,计算出gdpPercap的中位数,并对其进行可视化画出棒状图。

# Summarize the median gdpPercap by continent in 1952
by_continent<-gapminder %>% 
filter(year==1952) %>% 
group_by(continent) %>% 
summarize(medianGdpPercap=median(gdpPercap))

# Create a bar plot showing medianGdp by continent
ggplot(by_continent,aes(x=continent,y=medianGdpPercap))+
geom_col()

直方图

选取年份year1952的数据,通过pop / 1000000来新增变量pop_by_mil。然后绘制直方图,设置间隔为50。

gapminder_1952 <- gapminder %>%
  filter(year == 1952) %>%
  mutate(pop_by_mil = pop / 1000000)

# Create a histogram of population (pop_by_mil)
ggplot(gapminder_1952,aes(pop_by_mil))+
geom_histogram(bins=50)

也可以对x轴进行对数转换。选取年份year1952的数据,画出变量pop的直方图,并对x轴进行对数转换(这是Chapter.1的内容)。

gapminder_1952 <- gapminder %>%
  filter(year == 1952)

# Create a histogram of population (pop), with x on a log scale
ggplot(gapminder_1952,aes(x=pop))+
geom_histogram(bins=50)+
scale_x_log10()

箱图

选取年份为1952的数据,x轴为continent,y轴为gdpPercap画box plot,并对y轴进行对数转换。

gapminder_1952 <- gapminder %>%
  filter(year == 1952)

# Create a boxplot comparing gdpPercap among continents
ggplot(gapminder_1952,aes(x=continent,y=gdpPercap)) +
geom_boxplot()+
scale_y_log10()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值