这是一个可能做你想做的事的代码。
在这段代码中,我首先按时间对数据库进行排序。这一步很重要,因为我使用排序数据库的索引作为您的图的横坐标,而不是时间戳。然后,我按类型对数据框进行分组,并在正确的位置手动绘制每个组(使用排序后的索引)。最后,我重新定义刻度和刻度标签以给定格式显示日期(在这种情况下,我选择了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