python - 如何在子图内创建图?
问题描述
我正在尝试绘制 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 个水平对齐的图?
解决方案
- 使用
plt.subplots
, 并使用参数指定列ncols
数。 - 创建绘图时,使用
counter
索引正确ax
的ax=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()
推荐阅读
- java - 通过搜索子值firebase android获取列表中的uid
- wpf - 基于单元格的DataGrid行背景包含值WPF
- javascript - 错误:不再支持 Buffer.write(string, encoding, offset[, length])
- git - SSH : git 特殊存储库
- javascript - 如何找到 unicode 组合?
- javascript - TypeError: Object(...) 不是 react-redux 中的函数
- css - 具有绝对位置的居中子级与具有显示 flex 的父级
- opencv - 3d 点投影 2d 点错误
- spring - 骆驼 cxf 肥皂和 karaf 问题
- jenkins - 使用外部数据库管理 Jenkins 用户角色