首页 > 解决方案 > plt. 在子情节中仅适用于一个情节

问题描述

我是 python 新手,所以我希望我的问题足够好,我正在尝试基于两个不同的数据框创建两个子图。我的问题是,当我尝试定义标题和 xlim 时,它只适用于一个情节。

这是我的脚本:

fig, axes = plt.subplots(1,2,figsize=(18,6))

#Original data
df_codes.loc[:,float_cols_gb].T.plot(ax=axes[0])
plt.title('Original Data', size=(20))
plt.ylabel('Reflectence', size=(14))
plt.xlabel('Wavelength', size=(14))
plt.xlim(410,1004)

#filter  data
df_bl_codes.loc[:,float_cols_bl].T.plot(ax=axes[1])
plt.title( 'Filter', size=(20))
plt.ylabel('Reflectence', size=(14))
plt.xlabel('Wavelength', size=(14))
plt.xlim(410,1004)

我无法附加图像,因为我是这里的新用户,但结果是两个图,一个获取标题和 xlim(第 1 列中的那个),另一个没有 ttiles 和 xlim(第 0 列中的那个)。

我的最终目标:将 xlimand 也应用于子图中的每个图的标题。

标签: pythonmatplotlibsubplot

解决方案


让我们尝试了解正在发生的事情,并帮助您改进未来创建情节的方式。

线

fig, axes = plt.subplots(1,2,figsize=(18,6))

创建两个对象(Python 中的一切都是一个对象):一个matplotlib.pyplot.Figure对象和一个包含两个matplotlib.pyplot.Axes对象的列表。然后,当您执行类似plt.title('Original Data', size=(20)), 的操作时,matplotlib会将这个标题添加到它认为是当前 Axes对象的对象中——因为您没有告诉 matplotlib 这是哪个对象,它会假定它是它刚刚创建的数组中的第一个对象。除非您另有说明(使用plt.sca(),但有更好的方法),否则它将始终假设这一点,以后调用 toplt.title()将覆盖先前的值。

Axes要解决此问题,请直接在对象上使用内置方法。您可以通过索引axes列表来访问这些:

fig, axes = plt.subplots(1,2,figsize=(18,6))

#Original data
df_codes.loc[:,float_cols_gb].T.plot(ax=axes[0])
axes[0].title('Original Data', size=(20))
axes[0].set_ylabel('Reflectence', size=(14))
axes[0].set_xlabel('Wavelength', size=(14))
axes[0].set_xlim(410,1004)

#filter  data
df_bl_codes.loc[:,float_cols_bl].T.plot(ax=axes[1])
axes[1].set_title( 'Filter', size=(20))
axes[1].set_ylabel('Reflectence', size=(14))
axes[1].set_xlabel('Wavelength', size=(14))
axes[1].set_xlim(410,1004)

推荐阅读