Разделить ось X между линией и линейчатым графиком в Matplotlib Python - PullRequest
0 голосов
/ 27 февраля 2020

У меня есть следующий сценарий для создания фигуры с двумя вспомогательными участками: одним линейным графиком и одним линейчатым графиком.

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

1 Ответ

1 голос
/ 27 февраля 2020

Вот моя версия, основанная на 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...