這是一個可能做你想做的事的代碼。
在這段代碼中,我首先按時間對數據庫進行排序。這一步很重要,因爲我使用排序數據庫的索引作爲您的圖的橫座標,而不是時間戳。然後,我按類型對數據框進行分組,並在正確的位置手動繪製每個組(使用排序後的索引)。最後,我重新定義刻度和刻度標籤以給定格式顯示日期(在這種情況下,我選擇了MM/YYYY,但可以更改)。
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
types = ['ABC','BCD','PQR']*3
vals = [126,1587,141,10546,1733,173,107,780,88]
ts = [1414814371, 1414814371, 1406865621, 1422766793, 1422766793, 1425574861, 1396324799, 1396324799, 1401595199]
aset = zip(types, vals, ts)
df = pd.DataFrame(data=aset, columns=['Type', 'Value', 'Timestamp'])
df = df.sort(['Timestamp', 'Type'])
df['Date'] = df['Timestamp'].apply(lambda x: datetime.datetime.fromtimestamp(x).strftime('%m/%Y'))
groups = df.groupby('Type')
ngroups = len(groups)
colors = ['r', 'g', 'b']
fig = plt.figure()
ax = fig.add_subplot(111, position=[0.15, 0.15, 0.8, 0.8])
offset = 0.1
width = 1-2*offset
#
for j, group in enumerate(groups):
x = group[1].index+offset
y = group[1].Value
ax.bar(x, y, width=width, color=colors[j], label=group[0])
xmin, xmax = min(df.index), max(df.index)+1
ax.set_xlim([xmin, xmax])
ax.tick_params(axis='x', which='both', top='off', bottom='off')
plt.xticks(np.arange(xmin, xmax)+0.5, list(df['Date']), rotation=90)
ax.legend()
plt.show()
我希望這對你有效。這是我得到的輸出,給出我的數據庫的子集。
你嘗試,是你想要的,除了錯誤的標籤什麼的條形圖? – 2015-04-02 20:13:34
是標籤是不正確的,它應該顯示每個月份的單獨類型(如欄)。檢查這個http://postimg.org/image/5m9s2y2mr/ – user3930865 2015-04-02 20:17:47
它不能解決你的問題,但你不想在創建條形圖之前按'類型'進行分組? 'df.groupby('Type')。plot(x ='DateTime',y ='Value',linewidth = 2,kind ='bar')' – 2015-04-02 20:30:53