Python Panda多线图使用时间戳

编程入门 行业动态 更新时间:2024-10-27 20:30:23
本文介绍了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多线图使用时间戳

本文发布于:2023-10-28 08:52:01,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线图   时间   Python   Panda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!