Skip to main content
 首页 » 编程设计

python之带折线图的条形图之使用非数字索引

2024年10月01日6sharpest

我想在同一张图上显示数据框的条形图和表示总和的折线图。 我可以为索引为数字或文本的框架执行此操作。但它不适用于日期时间索引。 这是我使用的代码:

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