气泡图是具有第三个维度的散点图,第三维度通过散点的大小来表示。画气泡图至少需要三个维度的数据,分别是x,y和表示气泡大小的维度。下面用一个例子来说明,其中,x是人均GDP,y是预期寿命,圆圈大小表示人口,代码如下:
1 2 3 4 5 6 7 8 9 10 11
| # 导入包 library(ggplot2) library(dplyr)
#gapminder提供了数据集 library(gapminder) data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
# 最基本的气泡图 ggplot(data, aes(x=gdpPercap, y=lifeExp, size = pop)) + geom_point(alpha=0.7)
|

图1
控制圆的大小:scale_size()
我们需要在上一张图表上改进的第一件事是气泡大小。scale_size()
允许使用range
参数设置最小和最大圆圈的大小。请注意,您可以使用 自定义图例名称name
。
注意:圆圈经常重叠。为避免图表顶部出现大圆圈,您必须首先重新排序数据集,如下面的代码所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| library(ggplot2) library(dplyr)
library(gapminder) data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
# 基本气泡图 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(.1, 24), name="Population (M)")
|

图2
添加第四个维度:颜色
如果您的数据集中还有一个变量,为什么不使用圆形颜色显示它?这里使用各个国家的大陆来控制圆圈颜色:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| library(ggplot2) library(dplyr)
library(gapminder) data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
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, 24), name="Population (M)")
|

图3
整理自:https://r-graph-gallery.com/320-the-basis-of-bubble-plot.html