python - 如何在单个子图中绘制数字列表?
问题描述
我有 2 个数字列表及其轴。我需要将每个图绘制在一个子图中,以便这些图成为一个大子图。我怎样才能做到这一点?
我尝试了 for 循环,但它没有用。
这是我尝试过的:
import ruptures as rpt
import matplotlib.pyplot as plt
# make random data with 100 samples and 9 columns
n_samples, n_dims, sigma = 100, 9, 2
n_bkps = 4
signal, bkps = rpt.pw_constant(n_samples, n_dims, n_bkps, noise_std=sigma)
figs, axs = [], []
for i in range(signal.shape[1]):
points = signal[:,i]
# detection of change points
algo = rpt.Dynp(model='l2').fit(points)
result = algo.predict(n_bkps=2)
fig, ax = rpt.display(points, bkps, result, figsize=(15,3))
figs.append(fig)
axs.append(ax)
plt.show()
解决方案
我查看了ruptures.display() 的源代码,它接受传递给matplotlib 的**kwargs。这允许我们将输出重定向到单个图形,并且使用 gridspec,我们可以在该图形中定位各个子图:
import ruptures as rpt
import matplotlib.pyplot as plt
n_samples, n_dims, sigma = 100, 9, 2
n_bkps = 4
signal, bkps = rpt.pw_constant(n_samples, n_dims, n_bkps, noise_std=sigma)
#number of subplots
n_subpl = signal.shape[1]
#give figure a name to refer to it later
fig = plt.figure(num = "ruptures_figure", figsize=(8, 15))
#define grid of nrows x ncols
gs = fig.add_gridspec(n_subpl, 1)
for i in range(n_subpl):
points = signal[:,i]
algo = rpt.Dynp(model='l2').fit(points)
result = algo.predict(n_bkps=2)
#rpt.display(points, bkps, result)
#plot into predefined figure
_, curr_ax = rpt.display(points, bkps, result, num="ruptures_figure")
#position current subplot within grid
curr_ax[0].set_position(gs[i].get_position(fig))
curr_ax[0].set_subplotspec(gs[i])
plt.show()
样本输出:
推荐阅读
- reactjs - Windows 上的“REACT_APP_VERSION”不被识别为内部或外部命令
- python - 如何使用pymongo查找字符有限的结果
- swift - 停止将触摸事件传播到 Swift 后面的视图
- docker - 为什么我不能从 Google Cloud Build 中提取我的 docker 映像?
- gnu-parallel - Passing multiple parameters to GNU parallel
- python - 在实现逻辑回归模型时包括特征
- r - 为不同变量的特定值查找一个变量的范围
- go - Golang 频道 - 帮助我解决这个问题
- mysql - 我无法将我的数据与另一个表 MySQL 的关系复制
- google-cloud-platform - 数据流侧输入刷新