我编写了一个python程序,使用pandas从csv获取数据,并使用matplotlib绘制数据。我的代码如下:结果:
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轴,使其看起来不像彼此重叠?我已将日期和时间存储为数据框中的一列。
我的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
答案 0 :(得分:4)
试试这个:
import pylab as pl
pl.xticks(rotation = 90)
它会将标签旋转90度,从而消除重叠。
查看this link,其中介绍了如何使用fig.autofmt_xdate()
,并让matplotlib选择格式化日期的最佳方式。
将to_datetime()
和set_index
与DataFrame.plot()
:
df.Datetime=pd.to_datetime(df.Datetime)
df.set_index('Datetime')
df['Sensor Value'].plot()
pandas
然后会照顾好你的情节:
我的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