我想在同一个图表上显示数据框的条形图和表示总和的折线图。 我可以对索引为数字或文本的框架执行此操作。但它不适用于日期时间索引。 这是我使用的代码:
import datetime as dt
np.random.seed(1234)
data = np.random.randn(10, 2)
date = dt.datetime.today()
index_nums = range(10)
index_text = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k']
index_date = pd.date_range(date + dt.timedelta(days=-9), date)
a_nums = pd.DataFrame(columns=['a', 'b'], index=index_nums, data=data)
a_text = pd.DataFrame(columns=['a', 'b'], index=index_text, data=data)
a_date = pd.DataFrame(columns=['a', 'b'], index=index_date, data=data)
fig, ax = plt.subplots(3, 1)
ax = ax.ravel()
for i, a in enumerate([a_nums, a_text, a_date]):
a.plot.bar(stacked=True, ax=ax[i])
(a.sum(axis=1)).plot(c='k', ax=ax[i])
正如您所看到的,最后一个图表仅作为带有条形图图例的线条出现。并且日期缺失。
另外,如果我将最后一行替换为
ax[i].plot(a.sum(axis=1), c='k')
然后:
- 带index_nums的图表是一样的
- 带有index_text的图表引发错误
- 带有index_date的图表显示条形图,但不显示折线图。
fgo 我正在使用 pytho 3.6.2 pandas 0.20.3 和 matplotlib 2.0.2
最佳答案
在同一轴上绘制条形图和线图通常可能会出现问题,因为条形图将条形图放置在整数位置(0,1,2,...N-1
)而线图使用数值数据来确定纵坐标。
在问题的情况下,使用 range(10)
作为条形图和折线图的索引效果很好,因为这些正是条形图将使用的数字。使用文本也可以很好地工作,因为需要用数字替换它才能显示它,当然前 N 个整数用于此目的。
日期时间索引的条形图也使用前 N 个整数,而折线图将绘制日期。因此,根据哪个先出现,您只能看到折线图或条形图(通过相应地更改 xlimits,您实际上会看到另一个)。
一个简单的解决方案是首先绘制条形图,然后将线图的数据帧上的索引重置为数字。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np; np.random.seed(1234)
import datetime as dt
data = np.random.randn(10, 2)
date = dt.datetime.today()
index_date = pd.date_range(date + dt.timedelta(days=-9), date)
df = pd.DataFrame(columns=['a', 'b'], index=index_date, data=data)
fig, ax = plt.subplots(1, 1)
df.plot.bar(stacked=True, ax=ax)
df.sum(axis=1).reset_index().plot(ax=ax)
fig.autofmt_xdate()
plt.show()
或者,您可以照常绘制线图并使用 matplotlib 条形图,它接受数字位置。请参阅这个答案:Python making combined bar and line plot with secondary y-axis
关于python - 带折线图的条形图 - 使用非数字索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46643747/