首页 > 解决方案 > 如何在子图内创建图?

问题描述

我正在尝试绘制 5 个不同的、水平对齐的、具有不同k值的图,以便可以对它们进行比较。

我设法画了1个数字。但是当循环 5 次时,只有 1 个绘图出现:

from sklearn.neighbors import KNeighborsClassifier
import mglearn
import matplotlib.pyplot as plt

clf = KNeighborsClassifier(n_neighbors=3)
clf.fit(X_test, c_test)

for counter in range(5):    
    mglearn.discrete_scatter(X_test[:,0], X_test[:,1], c_test)
    plt.legend(["Class 0", "Class 1"], loc=4)
    plt.xlabel("First feature")
    plt.ylabel("Second feature")

如何显示 5 个水平对齐的图?

标签: pythonmatplotlib

解决方案


  • 使用plt.subplots, 并使用参数指定列ncols数。
  • 创建绘图时,使用counter索引正确axax=ax[counter]
  • 添加plt.tight_layout()以添加图之间的间距,否则ylabels可能与相邻图重叠。
fig, ax = plt.subplots(ncols=5, figsize=(20, 6))  # create subplot with x number of columns
for counter in range(5):
    mglearn.discrete_scatter(X_test[:,0], X_test[:,1], c_test, ax=ax[counter])
    plt.legend(["Class 0", "Class 1"], loc=4)
    plt.xlabel("First feature")
    plt.ylabel("Second feature")
plt.tight_layout()  # this will help create proper spacing between the plots.
plt.show()

例子

import pandas as pd
import numpy as np

# sinusoidal sample data
sample_length = range(1, 4+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])

# plot with subplots
fig, ax = plt.subplots(ncols=4, figsize=(20, 5))
for i, col in enumerate(df.columns):
    d = pd.DataFrame(df[col])
    sns.lineplot(x=d.index, y=col, data=d, ax=ax[i])

plt.tight_layout()
plt.show()

在此处输入图像描述


推荐阅读