2017-10-09 100 views
2

我想在同一图表上显示数据框的条形图和表示总和的折线图。 我可以为索引是数字或文本的框架做到这一点。但它不适用于日期时间索引。 这里是我使用的代码:带折线图的条形图 - 使用非数字索引

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]) 

enter image description here

正如你可以看到一个图表来,只有与条形图图例行。日期不见了。

另外,如果我与

ax[i].plot(a.sum(axis=1), c='k') 

然后替换的最后一行:

  • 与index_nums图是同一
  • 与index_text图表引发错误
  • 图表用index_date显示条形图,但不显示折线图。

FGO我使用pytho 3.6.2熊猫0.20.3和matplotlib 2.0.2

+0

退出线'ax.plot(a.sum(axis = 1),c ='k')'并添加必要的导入,问题中的代码正常工作,对于数字,文本和日期索引。因此,你不清楚你在问什么。 – ImportanceOfBeingErnest

+0

究竟是什么问题?这两块地块看起来和我很相似,都没有使用任何日期时间索引。 – Goyo

+0

所以现在看来​​唯一的问题是日期时间情节,其他两个按预期工作。你可以编辑这个问题,不要有太多分散注意力的东西吗? – ImportanceOfBeingErnest

回答

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

+0

非常感谢。有时候做不同类型的情节有点违反直觉。令我惊讶的是,第二种方法'ax [i] .plot(a.sum(axis = 1),c ='k')'实际上引发了文本索引的错误。 –

+0

matplotlib'plot'需要参数x和y,'ax.plot(范围(len(df)),df。sum(axis = 1))'或单个数组作为y参数,'ax.plot(df.sum(axis = 1).values)'。 – ImportanceOfBeingErnest