我正在尝试使用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多线图使用时间戳
发布评论