铂。在子图中仅适用于一个地块

plt. in subplot works only for one plot

我是 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(第 1 列中的那个)第 0 列)。

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

对于子图,您应该使用轴实例。 尝试执行以下操作:

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

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

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

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

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

创建两个对象(Python中的所有东西都是一个对象):一个matplotlib.pyplot.Figure object, and a list containing two matplotlib.pyplot.Axes objects. When you then do something like plt.title('Original Data', size=(20)), matplotlib will add this title to what it deems to be the current Axes object—as you haven't told matplotlib which object this is, it will assume it is the first one in the array it just created. Unless you tell it otherwise (with plt.sca(),但是有更好的方法),它将总是假设这,以及稍后对 plt.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)