如何使用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