【问题标题】:How to print multiple plots together in python?如何在python中一起打印多个图?
【发布时间】:2021-04-24 13:16:13
【问题描述】:

我试图在 7 行 6 列中打印大约 42 个图,但是 jupyter notebook 中的打印输出显示所有图一个在另一个之下。我希望它们以 (7,6) 格式进行比较。我正在使用 matplotlib.subplot2grid() 函数。

注意:我没有收到任何错误,并且我的代码有效,但是这些图是一个在另一个之下,而不是在一个网格/矩阵形式中。 这是我的代码:

def draw_umap(n_neighbors=15, min_dist=0.1, n_components=2, metric='euclidean', title=''):
fit = umap.UMAP(
    n_neighbors=n_neighbors,
    min_dist=min_dist,
    n_components=n_components,
    metric=metric
)
u = fit.fit_transform(df);
plots = []
plt.figure(0)
fig = plt.figure()
fig.set_figheight(10)
fig.set_figwidth(10)
for i in range(7):
    for j in range(6):
        plt.subplot2grid((7,6), (i,j), rowspan=7, colspan=6)
        
    plt.scatter(u[:,0], u[:,1], c= df.iloc[:,0])
        
    plt.title(title, fontsize=8)

n=range(7)
d=range(6)

for n in n_neighbors:
    for d in dist:
        draw_umap(n_neighbors=n, min_dist=d, title="n_neighbors={}".format(n) + " min_dist={}".format(d))

我确实参考了这个post 以获取网格中的图并遵循代码。 我还参考了这个post,并修改了我的代码以获取无花果的大小。

使用 Seaborn 有没有更好的方法来做到这一点?

我在这里缺少什么?请帮忙!

【问题讨论】:

  • 您介意检查您提供的代码中的缩进是否正确吗?对我来说,draw_umap 函数在哪里结束以及plt.scatterplt.title 是否应该在for j in range(6) 循环中并不完全清楚。另外,我注意到n=range(7); d=range(6) 是多余的,因为它们在以下循环中被覆盖。
  • 缩进是对的。我认为,这只是 jupyter notebook 中的一个问题。我会仔细检查范围值。谢谢!

标签: python matplotlib jupyter-notebook visualization


【解决方案1】:

您链接的两个问题都包含看似比必要复杂的解决方案。请注意,subplot2grid 仅在您想创建不同大小的子图时才有用,我知道这不是您的情况。另请注意,根据the docs使用 GridSpec,通常首选 GridSpec 演示中的演示,我也建议仅在您想创建不同大小的子图时使用此功能。

创建大小相等的子图网格的简单方法是使用plt.subplots,它返回一个Axes 数组,您可以通过该数组循环绘制数据,如this answer 所示。该解决方案在您的情况下应该可以正常工作,因为您在 7 x 6 的网格中绘制 42 个图。但问题是,在许多情况下,您可能会发现自己不需要网格的所有 Axes,因此您将结束在你的图中添加了一些空帧。

因此,我建议使用更通用的解决方案,首先创建一个空图形,然后将每个 Axes 添加到 fig.add_subplot,如下例所示:

import numpy as np               # v 1.19.2
import matplotlib.pyplot as plt  # v 3.3.4

# Create sample dataset
rng = np.random.default_rng(seed=1)  # random number generator
nvars = 8
nobs = 50
xs = rng.uniform(size=(nvars, nobs))
ys = rng.normal(size=(nvars, nobs))

# Create figure with appropriate space between subplots
fig = plt.figure(figsize=(10, 8))
fig.subplots_adjust(hspace=0.4, wspace=0.3)

# Plot data by looping through arrays of variables and list of colors
colors = plt.get_cmap('tab10').colors
for idx, x, y, color in zip(range(len(xs)), xs, ys, colors):
    ax = fig.add_subplot(3, 3, idx+1)
    ax.scatter(x, y, color=color)

这也可以在 seaborn 中完成,但我需要查看您的数据集是什么样子才能提供与您的案例相关的解决方案。



您可以在second solution in this answer 中找到此方法的更详细示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2011-08-01
    • 1970-01-01
    相关资源
    最近更新 更多