简体   繁体   English

将x轴作为matplotlib中的日期绘制

[英]plot x-axis as date in matplotlib

I am trying to perform some analysis on data. 我正在尝试对数据进行一些分析。 I got csv file and I convert it into pandas dataframe. 我有csv文件,我将其转换为pandas数据帧。 the data looks like this. 数据看起来像这样。 Its has several columns, but I am trying to draw x-axis as date column. 它有几列,但我试图绘制x轴作为日期列。 .

the pandas dataframe looks like this 熊猫数据框看起来像这样

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

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. 为此我试图将x-asis刻度作为日期。 since the minimum date in date column is 2011-01-01 and maximum date is 2012-04-20. 由于日期栏中的最短日期为2011-01-01,最长日期为2012-04-20。

I tried something like this 我试过这样的事

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')

But I am getting this error. 但是我收到了这个错误。

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

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. 有人可以帮我画出x轴作为日期列。 I would be grateful. 我会很感激。

Set the index to the datetime series 将索引设置为datetime系列

If you set the index to the datetime series matplotlib will handle the x axis for you. 如果将索引设置为datetime系列,matplotlib将为您处理x轴。 Here is a minimal example of how you might deal with this visualization. 以下是如何处理此可视化的最小示例。

Simple example: 简单的例子:

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)

This will yield a plot that looks like the following: 这将产生如下图:

在此输入图像描述

Setting the index makes things easier 设置索引会使事情变得更容易

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. 重要的一点是,将DataFrame索引设置为datetime系列允许matplotlib在时间序列数据上处理x轴而没有太多帮助。

Follow this link for detailed explanation on spacing axis ticks (specifically dates) 有关间距轴刻度(特别是日期)的详细说明,请点击此链接

You missed a ' line 12. It cause the SyntaxError. 你错过了'第12行。它导致了SyntaxError。

This should correct the error. 这应该纠正错误。

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') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM