【问题标题】:plt. in subplot works only for one plotplt.在子情节中仅适用于一个情节
【发布时间】:2020-04-18 07:53:01
【问题描述】:

我是 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 以及标题应用于子图中的每个图。

【问题讨论】:

标签: python matplotlib subplot


【解决方案1】:

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

线

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

创建两个对象(Python 中的一切都是一个对象):一个matplotlib.pyplot.Figure 对象和一个包含两个matplotlib.pyplot.Axes 对象的列表。然后,当您执行 plt.title('Original Data', size=(20)) 之类的操作时,matplotlib 会将这个标题添加到它认为是 current Axes 的对象中——因为您没有告诉 matplotlib 这是哪个对象,它将假定它是它刚刚创建的数组中的第一个。除非您另有说明(使用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)

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-02
      • 2020-06-14
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      相关资源
      最近更新 更多