哑铃图或连接点图是可视化多个组随时间变化的好方法。哑铃图是分组条形图的绝佳替代品,因为哑铃图在纸张上使用的墨水少得多,而且易于理解。喜欢的小伙伴可以关注个人公众号R语言数据分析指南,持续分享更多优质资源
哑铃图或连接点图是可视化多个组随时间变化的好方法。哑铃图是分组条形图的绝佳替代品,因为哑铃图在纸张上使用的墨水少得多,而且易于理解
使用gapminder数据集并制作哑铃图,以显示多个国家的预期寿命值在1952年至2007年之间的变化
library(tidyverse)
library(gapminder)
绘制哑铃图以比较所有欧洲国家从1952年到2007年的预期寿命变化。为了将这些点连接起来,需要指定连接的行或国家。因此创建一个新变量,用于指定与每个国家相对应的组
df <- gapminder %>%
filter(year %in% c(1952,2007)) %>%
filter(continent=="Europe") %>%
mutate(paired = rep(1:(n()/2),each=2),
year=factor(year))
让我们首先根据分组绘图,以显示每个国家在两年之间的预期寿命变化
ggplot(df,aes(x= lifeExp, y= reorder(country,lifeExp), fill=year)) +
geom_col(position="dodge")+
labs(y="Country")
我们可以看到,分组的barplot臃肿,并且不容易理解数据要表达的意思
df %>%
ggplot(aes(x= lifeExp, y= country)) +
geom_line(aes(group = paired))+
geom_point(aes(color=year), size=4) +
theme(legend.position="top")
使用geom_line()和geom_point()函数绘制哑铃图
df %>%
ggplot(aes(x= lifeExp, y= reorder(country,lifeExp))) +
geom_line(aes(group = paired))+
geom_point(aes(color=year), size=4) +
labs(y="country")
ggplot2重新排序哑铃图
使用reorder()函数根据预期寿命值对哑铃图进行重新排序,使结果更加直观
df %>%
ggplot(aes(x= lifeExp, y= reorder(country,lifeExp))) +
geom_line(aes(group = paired),color="grey")+
geom_point(aes(color=year), size=5) +
labs(y="country")+
theme_classic()+
theme(legend.position="top") +
scale_color_brewer(palette="Accent", direction=-1)