在matplotlib中将x轴绘制为日期 [英] plot x-axis as date in matplotlib

查看:781
本文介绍了在matplotlib中将x轴绘制为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对数据进行一些分析.我得到了csv文件,并将其转换为pandas数据框.数据看起来像这样.它有几列,但我试图将x轴绘制为日期列. .

I am trying to perform some analysis on data. I got csv file and I convert it into pandas dataframe. the data looks like this. Its has several columns, but I am trying to draw x-axis as date column. .

熊猫数据框如下

print (df.head(10)

    cus-id        date       value_limit
0   10173         2011-06-12        455
1   95062         2011-09-11        455
2   171081        2011-07-05        212
3   122867        2011-08-18        123
4   107186        2011-11-23        334
5   171085        2011-09-02        376
6   169767        2011-07-03        34
7   80170         2011-03-23        34
8   154178        2011-10-02        34
9   3494          2011-01-01        34

我正在尝试绘制日期数据,因为同一日期有多个值.为此,我试图将x-asis刻度绘制为日期.由于日期"列中的最小日期为2011-01-01,最大日期为2012-04-20.

I am trying to plot date data because there are multiple values for same date. for this purpose I am trying to plot x-asis ticks as date. since the minimum date in date column is 2011-01-01 and maximum date is 2012-04-20.

我尝试过类似的事情

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
import matplotlib.dates as mdates

df = pd.read_csv('rio_data.csv', delimiter=',')
print (df.head(10))
d = []
for dat in df.date:
    # print (dat)
    d.append(datetime.strptime(df['date'], '%Y-%m-%d'))
days = dates.DayLocator()
datemin = datetime(2011, 1, 1)
datemax = datetime(2012, 4, 20) 
fig = plt.figure()
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(days)
ax.set_xlim(datemin, datemax)
ax.set_ylabel('Count values')

但是我收到此错误.

 AttributeError: 'DataFrame' object has no attribute 'date'

我正在尝试将日期绘制为x轴,它应该看起来像这样.

I am trying to draw date as x-axis, it should look like this.

有人可以帮我绘制x轴作为日期列吗?我会很感激.

Can someone help me to draw the x-axis as date column. I would be grateful.

推荐答案

将索引设置为日期时间序列

如果将索引设置为日期时间序列,则matplotlib将为您处理x轴.这是您如何处理此可视化效果的最小示例.

Set the index to the datetime series

If you set the index to the datetime series matplotlib will handle the x axis for you. Here is a minimal example of how you might deal with this visualization.

import pandas as pd
import matplotlib.pyplot as plt

date_time = ["2011-09-01", "2011-08-01", "2011-07-01", "2011-06-01", "2011-05-01"]
date_time = pd.to_datetime(date_time)
temp = [2, 4, 6, 4, 6]

DF = pd.DataFrame()
DF['temp'] = temp
DF = DF.set_index(date_time)

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.3)
plt.xticks(rotation=90)
plt.plot(DF)

这将产生一个如下图所示的图:

重要的一点是,将DataFrame索引设置为datetime序列可以使matplotlib在时间序列数据上处理x轴而无需太多帮助.

The important note is that setting the DataFrame index to the datetime series allows matplotlib to deal with x axis on time series data without much help.

关注此链接详细了解间距轴刻度(特别是日期)

这篇关于在matplotlib中将x轴绘制为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆