python - 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 也应用于子图中的每个图的标题。
解决方案
让我们尝试了解正在发生的事情,并帮助您改进未来创建情节的方式。
线
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)
推荐阅读
- linkedin - 使用 Linkedin 进行单点登录不断询问使用 API v1 登录的用户的授权
- sql - 如何在 SQL 的两个表中获取具有不常见值的行?
- wordpress - 是否有任何条件可以在联系表格 7 的单选按钮中选择最多 3 个字段
- inno-setup - 单击 Inno Setup 中的 Finish 按钮后,根据自定义复选框运行文件和程序
- javascript - 如果对象键存在,我如何格式化响应?
- python - 一列中的更改也应该在另一列中进行更改
- r - 如何在 R 中为 6000 次迭代构建重复循环?
- node.js - Express 4,将 req.path 与 URL 参数匹配
- java - JSON Volley PUT 请求覆盖一切
- mysql - Sails.js:如何为记录做更新日期?