【Python】在同一图形中的绘制多个子图

文摘   2023-06-11 08:00   江苏  






01


引言



有时我们需要并排绘制两个图形,这不仅是为了更好地利用空间,而且主要是因为为了更加直观地对比分析数据。其实在python中可以利用subplot来实现上述功能。

闲话少说,我们直接开始吧!




02


准备工作


这里,我们不妨先来举个例子,比方说,我们正在分析一家出租车公司的出行分布,假设我们想知道在ManhattanBrooklyn的皮卡车的出行距离有什么不同。
import seaborn as sns# Load datasetdf = sns.load_dataset('taxis')

加载后的结果如下:

接着,我们使用以下代码来挑选我们关注的ManhattanBrooklyn的样本数据,如下:

# Brooklyn travelsdf_bklyn = df.query(' pickup_borough == "Brooklyn" ')# Manhattan Travelsdf_mhtn = df.query(' pickup_borough == "Manhattan" ')





03


绘制


接着就是鉴定奇迹的时刻了。首先,我们要创建一个图形,并指示我们想要的行和列的数量(在下面的示例中,它是同一行上的两个图)。

# Creating a grid figure with matplotlibfig, my_grid = plt.subplots(nrows=1, ncols=2, figsize=(18,8))

然后我们应该创建我们的子图,并使用切片表示法指示这些子图在网格中的位置。样例如下:

# Histograms# Plot 1g1 = sns.histplot(data=df_bklyn, x='distance', ax=my_grid[0])# Title of the Plot 1g1.set_title('Histogram of the travels beginning in Brooklyn')
# Plot 2g2 = sns.histplot(data=df_mhtn, x='distance', ax=my_grid[1])# Title of the Plot 2g2.set_title('Histogram of the travels beginning in Manhattan');

结果如下:






04


扩展


matplotlib的多个子图的绘制方法非常相似,但让我们观察下在对其进行编码时看看有什么不同。

首先来看一个一行三列的例子,如下:

# Creating a grid figure with matplotlib SINGLE ROW EXAMPLEfig, (g1, g2, g3) = plt.subplots(nrows=1, ncols=3, figsize=(18,8))

但如果我们有多行,此时需要使用元组构成的列表,列表中的每一行表示一个元组。

# Creating a grid figure with matplotlib MULTIPLE ROWS EXAMPLEfig, [(g1, g2, g3), (g4, g5, g6)] = plt.subplots(nrows=2, ncols=3, figsize=(18,8))
让我们看看距离纽约市4个不同社区的直方图的一个实际例子。请注意,这里不再需要使用ax参数。
# Creating a grid figure with matplotlibfig, [(g1, g2), (g3, g4)] = plt.subplots(nrows=2, ncols=2, figsize=(18,8))# Histograms# Plot 1g1.hist(data=df_bklyn, x='distance')# Title of the Plot 1g1.set_title('Histogram of the travels beginning in Brooklyn')# Plot 2g2.hist(data=df_mhtn, x='distance')# Title of the Plot 2g2.set_title('Histogram of the travels beginning in Manhattan')# Plot 3g3.hist(data=df_queens, x='distance')# Title of the Plot 3g3.set_title('Histogram of the travels beginning in Queens')# Plot 4g4.hist(data=df_bronx, x='distance')# Title of the Plot 4g4.set_title('Histogram of the travels beginning in Bronx');

运行结果如下:








05


总结


帖子很短,但里面的技巧非常有用。在实际应用中,经常不得不回来重新思考如何做到这一点,特此记录,方便下次查看。最后希望这篇文章帮助初学者轻松地在同一个图形中绘制多个子图。

您学废了嘛?






点击上方小卡片关注我






新年寄语:

所求皆如愿,

所行皆坦途。

多喜乐,长安宁。

AI算法之道
一个专注于深度学习、计算机视觉和自动驾驶感知算法的公众号,涵盖视觉CV、神经网络、模式识别等方面,包括相应的硬件和软件配置,以及开源项目等。
 最新文章