我编写了一个 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 轴,使其看起来不像彼此重叠?我已将日期和时间作为一列存储在我的数据框中。
我的数据框看起来像这样:
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
最佳答案
黑客方式
试试这个:
import pylab as pl
pl.xticks(rotation = 90)
它将标签旋转 90 度,从而消除重叠。
更简洁的方式
查看 this link其中描述了如何使用 fig.autofmt_xdate()
并让 matplotlib 选择格式化日期的最佳方式。
Pandas 之路
使用to_datetime()
和 set_index
与 DataFrame.plot()
:
df.Datetime=pd.to_datetime(df.Datetime)
df.set_index('Datetime')
df['Sensor Value'].plot()
pandas
然后会小心地为您绘制它:
我的数据框看起来像这样:
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
关于python - 如何使用 matplotlib 从 csv 绘制特定日期和时间的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42350381/