将Pandas线图转换为带月份名称的条形图

2024-10-08 19:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pythonpanda将线garph转换为条形图。在

这是我的代码,它可以根据我的要求给出完美的线图。在

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()

这是我的数据帧 http://postimg.org/image/75uy0dntf/

这是我从上面的代码输出的线图。 http://postimg.org/image/vc5lbi9xv/

我想画条形图而不是线图,月份名称在x轴上,值在y轴上。我要彩色条形图。在

尝试

^{pr2}$

它在x轴上给出了带有日期和时间(而不是月份和年份)的不正确条形图。谢谢你的帮助。在


Tags: 代码orgimagehttpdfdatetimepltconn
1条回答
网友
1楼 · 发布于 2024-10-08 19:24:18

这里有一个代码,可以做你想做的。在

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

相关问题 更多 >

    热门问题