如何使用matplotlib从CSV绘制特定日期和时间的数据? [英] How to plot data from csv for specific date and time using matplotlib?

查看:161
本文介绍了如何使用matplotlib从CSV绘制特定日期和时间的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个python程序,使用pandas从csv获取数据,并使用matplotlib绘制数据.我的代码如下所示:

I have written a python program to get data from csv using pandas and plot the data using matplotlib. My code is below with result:

import pandas as pd
import datetime
import csv
import matplotlib.pyplot as plt
headers = ['Sensor Value','Date','Time']
df = pd.read_csv('C:/Users\Lala Rushan\Downloads\DataLog.CSV',parse_dates=     {"Datetime" : [1,2]},names=headers)
#pd.to_datetime(df['Date'] + ' ' + df['Time'])
#df.apply(lambda r : pd.datetime.combine(r['Date'],r['Time']),)
print (df)

#f = plt.figure(figsize=(10, 10))
df.plot(x='Datetime',y='Sensor Value',) # figure.gca means "get current axis"
plt.title('Title here!', color='black')
plt.tight_layout()
plt._show()

现在您可以看到x轴看起来很恐怖.如何绘制单个日期和时间间隔的x轴,以使其看起来不像彼此重叠?我将日期和时间都存储为数据框中的一列.

Now as you can see the x-axis looks horrible. How can I plot the x-axis for a single date and time interval so that it does not looks like overlapping each other? I have stored both date and time as one column in my dataframe.

我的数据框如下:

                       Datetime  Sensor Value
0     2017/02/17  19:06:17.188             2
1     2017/02/17  19:06:22.360            72
2     2017/02/17  19:06:27.348            72
3     2017/02/17  19:06:32.482            72
4     2017/02/17  19:06:37.515            74
5     2017/02/17  19:06:42.580            70

推荐答案

怪异方式

尝试一下:

Hacky way

Try this:

import pylab as pl
pl.xticks(rotation = 90)

它将标签旋转90度,从而消除重叠.

It will rotate the labels by 90 degrees, thus eliminating overlap.

查看此链接,其中介绍如何使用fig.autofmt_xdate()并让matplotlib选择格式化日期的最佳方法.

Check out this link which describes how to use fig.autofmt_xdate() and let matplotlib pick the best way to format your dates.

DataFrame.plot()上使用 to_datetime() set_index:

Use to_datetime() and set_index with DataFrame.plot():

df.Datetime=pd.to_datetime(df.Datetime)
df.set_index('Datetime')
df['Sensor Value'].plot()

pandas然后会小心地为您绘制好它:

pandas will then take care to plot it nicely for you:

我的数据框如下:

                      Datetime  Sensor Value
0     2017/02/17  19:06:17.188             2
1     2017/02/17  19:06:22.360            72
2     2017/02/17  19:06:27.348            72
3     2017/02/17  19:06:32.482            72
4     2017/02/17  19:06:37.515            74
5     2017/02/17  19:06:42.580            70

这篇关于如何使用matplotlib从CSV绘制特定日期和时间的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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