使用matplotlib包绘制气泡图
# libraries
import matplotlib.pyplot as plt
import numpy as np
# create data
x = np.random.rand(40)
y = np.random.rand(40)
z = np.random.rand(40)
# use the scatter function
# 绘制基础气泡图
# s=z*1000参数设置气泡的大小
plt.scatter(x, y, s=z*1000, alpha=0.5)
# show the graph
plt.show()
# Change color with c and alpha
# 设置c="red"参数更改气泡的颜色
plt.scatter(x, y, s=z*4000, c="red", alpha=0.4)
# show the graph
plt.show()
# Change shape with marker
# 设置marker="D"参数更改气泡的形状
plt.scatter(x, y, s=z*4000, marker="D")
# show the graph
plt.show()
# Change line around dot
# 设置linewidth=6参数更改气泡的边框大小
plt.scatter(x, y, s=z*4000, c="green", alpha=0.4, linewidth=6)
# show the graph
plt.show()
# Change color with c and transparency with alpha.
# I map the color to the X axis value.
plt.scatter(x, y, s=z*2000, c=x, cmap="Accent", alpha=0.4, edgecolors="grey", linewidth=2)
# Add titles (main and on axis)
# 添加坐标轴和标题信息
plt.xlabel("the X axis")
plt.ylabel("the Y axis")
plt.title("A colored bubble plot")
# Show the graph
plt.show()
使用seaborn包绘制气泡图
# libraries
import matplotlib.pyplot as plt
import seaborn as sns
from gapminder import gapminder # import data set
# Control figure size for this notebook:
plt.rcParams['figure.figsize'] = [8, 8]
# data
data = gapminder.loc[gapminder.year == 2007]
data.head()
|
country |
continent |
year |
lifeExp |
pop |
gdpPercap |
11 |
Afghanistan |
Asia |
2007 |
43.828 |
31889923 |
974.580338 |
23 |
Albania |
Europe |
2007 |
76.423 |
3600523 |
5937.029526 |
35 |
Algeria |
Africa |
2007 |
72.301 |
33333216 |
6223.367465 |
47 |
Angola |
Africa |
2007 |
42.731 |
12420476 |
4797.231267 |
59 |
Argentina |
Americas |
2007 |
75.320 |
40301927 |
12779.379640 |
# use the scatterplot function to build the bubble map
sns.scatterplot(data=data, x="gdpPercap", y="lifeExp", size="pop", legend=False)
# show the graph
plt.show()
# use the scatterplot function
# 设置sizes=(20, 800)参数控制气泡大小的范围
sns.scatterplot(data=data, x="gdpPercap", y="lifeExp", size="pop", alpha=0.5, sizes=(20, 800))
# show the graph
plt.show()
# use the scatterplot function
# 设置hue="continent"参数控制分组颜色
sns.scatterplot(data=data, x="gdpPercap", y="lifeExp", size="pop", hue="continent", alpha=0.5, sizes=(20, 400))
# show the graph
plt.show()
# set seaborn "whitegrid" theme
sns.set_style("darkgrid")
# use the scatterplot function
sns.scatterplot(data=data, x="gdpPercap", y="lifeExp", size="pop",
hue="continent", palette="viridis",
edgecolors="black", alpha=0.5, sizes=(10, 1000))
# Add titles (main and on axis)
plt.xlabel("Gdp per Capita")
plt.ylabel("Life Expectancy")
# Locate the legend outside of the plot
# plt.legend(bbox_to_anchor=(1, 1), loc='upper left', fontsize=17)
# show the graph
plt.show()