Python Panda多线图使用时间戳 [英] Python Panda multi Line graph using time stamp

查看:219
本文介绍了Python Panda多线图使用时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python panda绘制图形,到目前为止我能够读取sqlite数据库。我无法使用时间戳生成图形。我想用python熊猫绘制多线图。我需要几个月(X轴)与价值(Y轴)图表为不同的线。

I am trying to draw graph using python panda, So far i am able to read sqlite database. I am not able to generate graph using timestamp. I want draw multi line graph using python panda. I want Months (X axis) vs Value (Y axis) graph for different line.

以下是我的数据框输出(df):

Below is my output of data frame(df):

这里是我的代码

import sqlite3
from pylab import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt


conn = sqlite3.connect('Metrics.db')
df = pd.read_sql("SELECT * FROM ABC", conn)

我试过使用df.plot(),但它没有用。

I tried using df.plot(), but it did not work.

预先感谢您。

推荐答案

好像有两个不同的目标。一种是按'类型'对数据进行分组,并分别绘制每条线。为此,您可以使用 df.groupby(),然后循环遍历组:

It seems like there are two separate objectives. One is to group your data by 'Type' and plot each line separately. To do that, you can use df.groupby() and then loop through groups:

for key, grp in df.groupby('Type'):
    plt.plot(grp['Timestamp'], grp['Value'])

第二个问题是如何格式化时间戳以显示月份。为此,首先将时间戳转换为日期时间,然后使用格式化程序仅打印月份名称。

The second question is how to format your timestamps to display the month. To do this, first convert your timestamps into datetimes, then use a formatter to print only the month name.

以下是一些代码,结合我们已有的从第一部分:

Here's some code that does that, combined with what we already had from the first part:

df['date'] = [pd.to_datetime(t, unit='s') for t in df['Timestamp']]
for key, grp in df.groupby('Type'):
    plt.plot(grp['date'], grp['Value'])
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%B'))



<如果你想改变你的刻度标签格式,你可以调整参数到DateFormatter。

You can adjust the argument to DateFormatter if you want to change your tick label format.

这篇关于Python Panda多线图使用时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆