python - Python Matplotlib 中的线图和条形图共享 X 轴

标签 python matplotlib

我有以下脚本用于生成带有两个子图的图形:一个线图和一个条形图。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

plt.close('all')

np.random.seed(42)
n = 1000
idx = pd.date_range(end='2020-02-27', periods=n)
df = pd.Series(np.random.randint(-5, 5, n),
               index=idx)
curve = df.cumsum()
bars = df.resample('M').sum()

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

curve.plot(ax=ax1)
bars.plot(kind='bar', ax=ax2)
fig.set_tight_layout(True)

我想共享两个子图之间的 x 轴,但是命令 ax2 = Fig.add_subplot(212, sharex=ax1) 将导致线图出现空图,如下所示下图。 enter image description here

最佳答案

这是我基于 Matplotlib 的版本(没有用于绘图的 pandas api),可能会有帮助。

我明确设置了条形的宽度。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

%matplotlib inline

plt.close('all')

np.random.seed(42)
n = 1000
idx = pd.date_range(end='2020-02-27', periods=n)
df = pd.Series(np.random.randint(-5, 5, n), index=idx)
curve = df.cumsum()
bars = df.resample('M').sum()

#fig = plt.figure()
#ax1 = fig.add_subplot(211)
#ax2 = fig.add_subplot(212)
#curve.plot(ax=ax1)
#bars.plot(kind='bar', ax=ax2)

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw={'hspace': 0})
ax1.plot(curve.index, curve.values)
ax2.bar(bars.index, bars.values, width = (bars.index[0] - bars.index[1])/2)

fig.set_tight_layout(True)
_ = plt.xticks(bars.index, bars.index, rotation=90)

enter image description here

关于python - Python Matplotlib 中的线图和条形图共享 X 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60435125/

相关文章:

python - Matplotlib 曲面图显示不同值的相同颜色

Python DictWriter 编写 UTF-8 编码的 CSV 文件

Python:如何在 POST 请求中发送 html 代码

python - 如何修复Python类中的属性错误

python - 当 nan 在列表中排在第一位时 matplotlib 问题

python - 我有一个时间序列体积图。想要将另一列数据框强加为虚线

python - matplotlib 2d line line,=plot逗号意思

python - 不可散列类型 : 'list' in printing Tensorflow vector

python - Tensorflow 安装和导入正确,但在尝试使用时抛出异常

Python 读取麦克风而不使用 PyAudio