2015-04-02 86 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