2015-04-02 84 views
1

我正嘗試使用python熊貓將線條圖轉換爲條形圖。將熊貓線圖轉換爲月份名稱的條形圖

這是我的代碼,根據我的要求給出完美的線條圖。

conn = sqlite3.connect('Demo.db') 

collection = ['ABC','PQR'] 
df = pd.read_sql("SELECT * FROM Table where ...", conn) 
df['DateTime'] = df['Timestamp'].apply(lambda x: dt.datetime.fromtimestamp(x)) 


df.groupby('Type').plot(x='DateTime', y='Value',linewidth=2) 
plt.legend(collection) 
plt.show() 

這是我的數據幀DF http://postimg.org/image/75uy0dntf/

這裏是從上面的代碼我的線圖輸出。 http://postimg.org/image/vc5lbi9xv/

我想繪製條形圖而不是線圖。我想要在x軸上的月份名稱和在y軸上的值。我想要彩色條形圖。

嘗試做

df.plot(x='DateTime', y='Value',linewidth=2, kind='bar') 

plt.show() 

它給X軸與日期和時間(而不是月和年)不當條形圖。謝謝你的幫助。

+0

你嘗試,是你想要的,除了錯誤的標籤什麼的條形圖? – 2015-04-02 20:13:34

+0

是標籤是不正確的,它應該顯示每個月份的單獨類型(如欄)。檢查這個http://postimg.org/image/5m9s2y2mr/ – user3930865 2015-04-02 20:17:47

+0

它不能解決你的問題,但你不想在創建條形圖之前按'類型'進行分組? 'df.groupby('Type')。plot(x ='DateTime',y ='Value',linewidth = 2,kind ='bar')' – 2015-04-02 20:30:53

回答

0

這是一個可能做你想做的事的代碼。

在這段代碼中,我首先按時間對數據庫進行排序。這一步很重要,因爲我使用排序數據庫的索引作爲您的圖的橫座標,而不是時間戳。然後,我按類型對數據框進行分組,並在正確的位置手動繪製每個組(使用排序後的索引)。最後,我重新定義刻度和刻度標籤以給定格式顯示日期(在這種情況下,我選擇了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() 

我希望這對你有效。這是我得到的輸出,給出我的數據庫的子集。

enter image description here

+0

感謝您發表解答。你能告訴我如何得到月份名稱/年份而不是月份/年份。即April/2015 – user3930865 2015-04-09 17:40:21

+0

在'df ['Date']'的定義中,您可以自定義'strftime'來滿足您的需求。檢查此鏈接的所有可能性:https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior。在這種情況下,您可以使用''%b%Y''=>'2014年4月'或''%B%Y''=>'2014年4月'。如果標籤太長,您只能看到它的末端=>您可以調整軸的「位置」來解決這個問題,或者將標籤旋轉45度而不是90度。 – 2015-04-09 18:00:19