基本简介
气泡图(Bubble plot)是添加了第三维度的散点图,具体是将三维变量反映在二维平面上,第三维用点的大小来表示。当数据过多时,气泡会重叠。可以使用R语言ggplot2包的geom_point()函数绘制,其中aes()参数中应该提供三个参数:x,y和size。本文利用世界各国的预期寿命(y)和人均国内生产总值(x)来绘制,每个国家/地区的人口数通过圆圈大小表示(size)。
示例代码
#清空数据
rm(list=ls())
#加载所需要的函数
library(ggplot2)
library(dplyr)
library(gapminder)
#整理数据
data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
data
![](https://img.haomeiwen.com/i26315894/566f7ed01e1577c5.png)
#绘制基本气泡图
ggplot(data, aes(x=gdpPercap, y=lifeExp, size = pop)) +
geom_point(alpha=0.7)
data %>%
arrange(desc(pop)) %>%
mutate(country = factor(country, country)) %>%
ggplot(aes(x=gdpPercap, y=lifeExp, size = pop)) +
geom_point(alpha=0.5) +
scale_size(range = c(0.1, 10), name="Population (M)")
![](https://img.haomeiwen.com/i26315894/c58b4eabb6c08835.png)
![](https://img.haomeiwen.com/i26315894/cca60b82f52c7f8b.png)
#按照continent修改颜色
data %>%
arrange(desc(pop)) %>%
mutate(country = factor(country, country)) %>%
ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, color=continent)) +
geom_point(alpha=0.5) +
scale_size(range = c(.1, 10), name="Population (M)")
![](https://img.haomeiwen.com/i26315894/d7e7f7f20fc0cee3.png)
#进一步美化
data %>%
arrange(desc(pop)) %>%
mutate(country = factor(country, country)) %>%
ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, fill=continent)) +
geom_point(alpha=0.5, shape=21, color="black") +
scale_size(range = c(.1, 15), name="Population (M)") +
scale_fill_viridis(discrete=TRUE,option="A") +
theme_few() +
theme(legend.position="bottom") +
ylab("Life Expectancy") +
xlab("Gdp per Capita") +
theme(legend.position = "right")
![](https://img.haomeiwen.com/i26315894/5faa2fd57a45057b.png)
参考文献
[1] https://r-graph-gallery.com/320-the-basis-of-bubble-plot.html
网友评论