簡體   English   中英

為什么我的堆積條形圖中缺少條形 -- Python w/matplotlib

[英]Why are bars missing in my stacked bar chart -- Python w/matplotlib

全部。

我正在嘗試創建一個使用時間序列數據構建的堆積條形圖。 我的問題——如果我將我的數據繪制為時間序列(使用線條),那么一切正常,我會得到一個(凌亂的)時間序列圖,其中包含正確的日期。 但是,如果我嘗試將其繪制為堆積條形圖,我的日期會消失,並且不會出現任何條形圖。

我曾嘗試弄亂條形的索引、高度和寬度。 沒運氣。

這是我的代碼:

import pylab
import pandas as pd
import matplotlib.pyplot as plt

df1= pd.read_excel('pathway/filename.xls')
df1.set_index('TIME', inplace=True)


ax = df1.plot(kind="Bar", stacked=True)
ax.set_xlabel("Date")
ax.set_ylabel("Change in Yield")
df1.sum(axis=1).plot( ax=ax, color="k", title='Historical Decomposition -- 1 year -- One-Quarter Revision')
plt.axhline(y=0, color='r', linestyle='-')
plt.show()

如果我改變ax = df1.plot(kind="Bar", stacked=True)

ax = df1.plot(kind="line", stacked=False)

我得到:

如果我使用ax = df1.plot(kind="Bar", stacked=True)

我得到:

這里有什么想法嗎?

在不知道數據是什么樣子的情況下,我會嘗試這樣的事情:

#Import data here and generate DataFrame

print(df.head(5))

               A     B     C     D
DATE
2020-01-01 -0.01  0.06  0.40  0.45
2020-01-02 -0.02  0.05  0.39  0.42
2020-01-03 -0.03  0.04  0.38  0.39
2020-01-04 -0.04  0.03  0.37  0.36
2020-01-05 -0.05  0.02  0.36  0.33

f, ax = plt.subplots()
ax.bar(df.index, df['A'])
ax.bar(df.index, df['B'])
ax.bar(df.index, df['C'], bottom=df['B'])
ax.plot(df.index, df['D'], color='black', linewidth=2)
ax.set_xlabel('Date')
ax.set_ylabel('Change in Yield')
ax.axhline(y=0, color='r')
ax.set_xticks([])
ax.legend()
plt.show()

在此處輸入圖片說明

編輯::好的,我在這里找到了一種查看這篇文章的方法: 在同一個圖表上將 Pandas DataFrame 繪制為條形和線條

嘗試重置索引,使其成為一個單獨的列。 在我的示例中,它被稱為“日期”。 然后嘗試:

ax = df[['DATE','D']].plot(x='DATE',color='black')
df[['DATE','A','B','C']].plot(x='DATE', kind='bar',stacked=True,ax=ax)
ax.axhline(y=0, color='r')
ax.set_xticks([])
ax.set_xlabel('Date')
ax.set_ylabel('Change in Yield')
ax.legend()
plt.show()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM