python - matplotlib - pandas - 子图中的 twinx 轴没有 xlabel 和 xticks

标签 python pandas matplotlib plot subplot

我有一个类似的问题,之前已经回答过。但是,它在使用 Pandas 包时有所不同。

这是我之前的问题:matplotlib - No xlabel and xticks for twinx axes in subploted figures

所以,我的问题和上一个一样,是为什么在使用此 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()

最佳答案

我遇到了同样的问题,因为我混合使用 matplotlib 和 Pandas 制作的绘图。

你不应该用 Pandas 绘图,这里是你可以替换的方法:

pd.Series(range(10)).plot(ax=ax42)

ax42.plot(pd.Series(range(10))

关于python - matplotlib - pandas - 子图中的 twinx 轴没有 xlabel 和 xticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35249393/

相关文章:

python - 在 Pandas 中的 groupby 之后聚合具有不同功能的不同列集

python - Pandas 数据框的动态合并

Python3.5 ImportError : libpython3. 5m.so.1.0: 无法打开共享对象文件: No such file or directory

python - 使用 matplotlib 为 svg 线图创建工具提示

python - 修正牛顿差分插值法的递归python实现,在递归中获取部分返回值

javascript - bokehjs 点击回调

python - 我可以在 Python 中验证 JSON 模式中字符串的内容吗

python - np.where 具有多个条件

python - 比较 Pandas 系列中的前一个值和下一个值

python - 在 Matplotlib 中使用 SVG 作为刻度标签