使用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
# 繪制基礎(chǔ)氣泡圖
# s=z*1000參數(shù)設(shè)置氣泡的大小
plt.scatter(x, y, s=z*1000, alpha=0.5)
# show the graph
plt.show()

image.png
# Change color with c and alpha
# 設(shè)置c="red"參數(shù)更改氣泡的顏色
plt.scatter(x, y, s=z*4000, c="red", alpha=0.4)
# show the graph
plt.show()

image.png
# Change shape with marker
# 設(shè)置marker="D"參數(shù)更改氣泡的形狀
plt.scatter(x, y, s=z*4000, marker="D")
# show the graph
plt.show()

image.png
# Change line around dot
# 設(shè)置linewidth=6參數(shù)更改氣泡的邊框大小
plt.scatter(x, y, s=z*4000, c="green", alpha=0.4, linewidth=6)
# show the graph
plt.show()

image.png
# 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)
# 添加坐標(biāo)軸和標(biāo)題信息
plt.xlabel("the X axis")
plt.ylabel("the Y axis")
plt.title("A colored bubble plot")
# Show the graph
plt.show()

image.png
使用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()

image.png
# use the scatterplot function
# 設(shè)置sizes=(20, 800)參數(shù)控制氣泡大小的范圍
sns.scatterplot(data=data, x="gdpPercap", y="lifeExp", size="pop", alpha=0.5, sizes=(20, 800))
# show the graph
plt.show()

image.png
# use the scatterplot function
# 設(shè)置hue="continent"參數(shù)控制分組顏色
sns.scatterplot(data=data, x="gdpPercap", y="lifeExp", size="pop", hue="continent", alpha=0.5, sizes=(20, 400))
# show the graph
plt.show()

image.png
# 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()

image.png