Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force pandas xaxis datetime index using a specific format

my pandas dataframe looks like this:

                      data1   data2         data3
DateTime
....                                       
2016-04-18 16:16:53     -66       1       94.8654
2016-04-18 16:17:03     -67       1       94.8601
2016-04-18 16:17:13     -68       1       94.8410
2016-04-18 16:17:23     -69       1       94.8753
2016-04-18 16:17:33     -70       1       94.8535
2016-04-18 16:17:43     -71       1       94.8529
2016-04-18 16:17:53     -72       1       94.8702
....

After I plot it with

 plt.style.use('ggplot')
 df.plot(subplots=True, style=style, title='some title', grid=True, x_compat=True)

The plot is only showing hours.
1) How do I make it to show days as well?
2) How do I force it to show any format I want?

plot

like image 270
user97662 Avatar asked Jul 01 '16 22:07

user97662


People also ask

How do I move the datetime index in pandas?

shift() function shift index by desired number of time frequency increments. This method is for shifting the values of datetime-like indexes by a specified time increment a given number of times. This method is only implemented for datetime-like index classes, i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex.

What is PD To_datetime ()?

Pandas to_datetime() method helps to convert string Date time into Python Date time object. Syntax: pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', cache=False)


1 Answers

You have to use functions from matplotlib.dates module:

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

timeInd = pd.date_range(start = datetime(2016,4,17,23,0,0), 
 end = datetime(2016,4,20,1,0,0), freq = 'H')
d = {'data1': np.random.randn(len(timeInd)), 'data2': np.random.randn(len(timeInd)),
 'data3': np.random.randn(len(timeInd))}
df = pd.DataFrame(data = d, index = timeInd)  

plt.style.use('ggplot')
df.plot(subplots=True, grid=True, x_compat=True)
ax = plt.gca()
# set major ticks location every day
ax.xaxis.set_major_locator(mdates.DayLocator())
# set major ticks format
ax.xaxis.set_major_formatter(mdates.DateFormatter('\n\n\n%d.%m.%Y'))
# set minor ticks location every two hours
ax.xaxis.set_minor_locator(mdates.HourLocator(interval=2))
# set minor ticks format
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M:%S'))

# or just set together date and time for major ticks like
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y %H:%M:%S'))

plt.show()    

enter image description here

More examples here: http://matplotlib.org/examples/api/date_demo.html

like image 184
Serenity Avatar answered Oct 18 '22 03:10

Serenity