pandas 如何使用 matplotlib 为特定日期和时间绘制来自 csv 的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42350381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to plot data from csv for specific date and time using matplotlib?
提问by rushan
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:
我编写了一个 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()
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.
现在你可以看到 x 轴看起来很可怕。如何绘制单个日期和时间间隔的 x 轴,使其看起来不会相互重叠?我已将日期和时间存储为数据框中的一列。
My Dataframe looks like this:
我的数据框看起来像这样:
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
回答by Sebastian Wozny
Hacky way
黑客方式
Try this:
尝试这个:
import pylab as pl
pl.xticks(rotation = 90)
It will rotate the labels by 90 degrees, thus eliminating overlap.
它将标签旋转 90 度,从而消除重叠。
Cleaner way
清洁方式
Check out this linkwhich describes how to use fig.autofmt_xdate()
and let matplotlib pick the best way to format your dates.
查看此链接,其中描述了如何使用fig.autofmt_xdate()
并让 matplotlib 选择格式化日期的最佳方式。
Pandas way
Pandas方式
Use to_datetime()
and set_index
with DataFrame.plot()
:
使用to_datetime()
并set_index
用DataFrame.plot()
:
df.Datetime=pd.to_datetime(df.Datetime)
df.set_index('Datetime')
df['Sensor Value'].plot()
pandas
will then take care to plot it nicely for you:
pandas
然后会注意为您很好地绘制它:
my Dataframe looks like this:
我的数据框看起来像这样:
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