简体   繁体   English

使用时间戳的Python Panda多线图

[英]Python Panda multi Line graph using time stamp

I am trying to draw graph using python panda, So far i am able to read sqlite database. 我正在尝试使用python熊猫绘制图形,到目前为止,我已经能够读取sqlite数据库。 I am not able to generate graph using timestamp. 我无法使用时间戳生成图形。 I want draw multi line graph using python panda. 我想使用python熊猫绘制多线图。 I want Months (X axis) vs Value (Y axis) graph for different line. 我想要不同行的月(X轴)与值(Y轴)图。

Below is my output of data frame(df): 以下是我的数据帧(df)的输出:

在此处输入图片说明

Here is my code 这是我的代码

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)

I tried using df.plot(), but it did not work. 我尝试使用df.plot(),但是没有用。

Thank You in advance. 先感谢您。

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: 为此,可以使用df.groupby() ,然后遍历组:

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

You can adjust the argument to DateFormatter if you want to change your tick label format. 如果要更改刻度标签格式,可以将参数调整为DateFormatter。

The following will convert the data frame index into Pandas timestamps: 以下将数据帧索引转换为熊猫时间戳记:

import datetime

df.index = [pd.Timestamp(datetime.datetime.fromtimestamp(ts)) for ts in df.Timestamp]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM