python - 如何使用 matplotlib 从 csv 绘制特定日期和时间的数据?

标签 python pandas matplotlib

我编写了一个 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()

enter image description here

现在您可以看到 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_indexDataFrame.plot():

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

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

enter image description here

我的数据框看起来像这样:

                      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/

相关文章:

python - 如何在 Flask 中并行化任务?

python - 数据框映射练习

python - 汇总一列

Python pandas 按类别分组占总数的百分比

python - Pandas - key 存在时获取 key 错误

python - pandas groupby() 收到错误消息 "level > 0 only valid with MultiIndex"

python - matplotlib matshow xtick 标签在顶部和底部

python - 在 Matplotlib 3 中设置具有共享轴的物理方形子图

python - 如何向通过 Seaborn 热图渲染的混淆矩阵添加工具提示?

python - 运行 ipython 笔记本时缺少 pyzmq