01
引言
有时我们需要并排绘制两个图形,这不仅是为了更好地利用空间,而且主要是因为为了更加直观地对比分析数据。其实在python中可以利用subplot来实现上述功能。
02
准备工作
import seaborn as sns
# Load dataset
df = sns.load_dataset('taxis')
加载后的结果如下:
接着,我们使用以下代码来挑选我们关注的Manhattan和Brooklyn的样本数据,如下:
# Brooklyn travels
df_bklyn = df.query(' pickup_borough == "Brooklyn" ')
# Manhattan Travels
df_mhtn = df.query(' pickup_borough == "Manhattan" ')
03
绘制
接着就是鉴定奇迹的时刻了。首先,我们要创建一个图形,并指示我们想要的行和列的数量(在下面的示例中,它是同一行上的两个图)。
# Creating a grid figure with matplotlib
fig, my_grid = plt.subplots(nrows=1, ncols=2, figsize=(18,8))
然后我们应该创建我们的子图,并使用切片表示法指示这些子图在网格中的位置。样例如下:
# Histograms
# Plot 1
g1 = sns.histplot(data=df_bklyn, x='distance', ax=my_grid[0])
# Title of the Plot 1
g1.set_title('Histogram of the travels beginning in Brooklyn')
# Plot 2
g2 = sns.histplot(data=df_mhtn, x='distance', ax=my_grid[1])
# Title of the Plot 2
g2.set_title('Histogram of the travels beginning in Manhattan');
结果如下:
04
扩展
matplotlib的多个子图的绘制方法非常相似,但让我们观察下在对其进行编码时看看有什么不同。
首先来看一个一行三列的例子,如下:
# Creating a grid figure with matplotlib SINGLE ROW EXAMPLE
fig, (g1, g2, g3) = plt.subplots(nrows=1, ncols=3, figsize=(18,8))
但如果我们有多行,此时需要使用元组构成的列表,列表中的每一行表示一个元组。
# Creating a grid figure with matplotlib MULTIPLE ROWS EXAMPLE
fig,
# Creating a grid figure with matplotlib
fig, [(g1, g2), (g3, g4)] = plt.subplots(nrows=2, ncols=2, figsize=(18,8))
# Histograms
# Plot 1
g1.hist(data=df_bklyn, x='distance')
# Title of the Plot 1
g1.set_title('Histogram of the travels beginning in Brooklyn')
# Plot 2
g2.hist(data=df_mhtn, x='distance')
# Title of the Plot 2
g2.set_title('Histogram of the travels beginning in Manhattan')
# Plot 3
g3.hist(data=df_queens, x='distance')
# Title of the Plot 3
g3.set_title('Histogram of the travels beginning in Queens')
# Plot 4
g4.hist(data=df_bronx, x='distance')
# Title of the Plot 4
g4.set_title('Histogram of the travels beginning in Bronx');
运行结果如下:
05
总结
您学废了嘛?
点击上方小卡片关注我
新年寄语:
所求皆如愿,
所行皆坦途。
多喜乐,长安宁。