matplotlib - 熊猫 - 子图中的 twinx 轴没有 xlabel 和 xticks

Mil*_*lad 6 python plot matplotlib pandas subplot

我有一个类似的问题,以前回答过。但是,它与 Pandas 包的用法不同。

这是我之前的问题:matplotlib - 子图中的 twinx 轴没有 xlabel 和 xticks

所以,我和上一个一样的问题是,为什么在使用此 Python 代码时,第一行图不显示 xlabel 和 xticks。

两个注意事项:

  1. 我也使用了subplots而不是gridspec相同的结果。
  2. 如果您取消注释此代码中与在每个图中的轴上使用 Pandas 相关的任何注释行,则 xlabel 和 xticks 将消失!

import matplotlib.pyplot as plt
import matplotlib.gridspec as gspec
import numpy as np
import pandas as pd
from math import sqrt

fig = plt.figure() 
gs = gspec.GridSpec(2, 2)
gs.update(hspace=0.7, wspace=0.7)
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[1, 0])
ax4 = plt.subplot(gs[1, 1])


x1 = np.linspace(1,10,10)


ax12 = ax1.twinx()
ax1.set_xlabel("Fig1")
ax12.set_xlabel("Fig1")
ax1.set_ylabel("Y1")
ax12.set_ylabel("Y2")
# pd.Series(range(10)).plot(ax=ax1)
ax12.plot(x1, x1**3)




ax22 = ax2.twinx()
ax2.set_xlabel("Fig2")
ax22.set_xlabel("Fig2")
ax2.set_ylabel("Y3")
ax22.set_ylabel("Y4")
# pd.Series(range(10)).plot(ax=ax2)
ax22.plot(x1, x1**0.5)


ax32 = ax3.twinx()
ax3.set_xlabel("Fig3")
ax32.set_xlabel("Fig3")
ax3.set_ylabel("Y5")
ax32.set_ylabel("Y6")
# pd.Series(range(200)).plot(ax=ax3)



ax42 = ax4.twinx()
ax4.set_xlabel("Fig4")
ax42.set_xlabel("Fig4")
ax4.set_ylabel("Y7")
ax42.set_ylabel("Y8")
# pd.Series(range(10)).plot(ax=ax42)



plt.subplots_adjust(wspace=0.8, hspace=0.8)
plt.show()
Run Code Online (Sandbox Code Playgroud)

Pra*_*dit 0

正如 Scimonster 上面为我提到的,当我在创建 twinx 轴之前绘制所有熊猫时,它起作用了。

我在 twinx 中有一些图也来自 Pandas Dataframe 对象(x,t 图)。我在开始绘图之前创建了单独的列表,然后在绘制第一个 pandas 绘图后使用它们进行绘图。

总结我的工作流程是 1. 为 twinx 图创建列表 2. 打开图并用法线轴绘制所有 pandas 图。3. 创建双轴 4. 在双轴上绘制列表

幸运的是,这个流程对我有用