Formatting datetime xlabels in matplotlib (pandas df.plot() method)

matplotlib plot timestamp
pandas plot
pandas plot datetime
matplotlib format time axis
ax xaxis_date
plot date vs value in python
format xlabel matplotlib
view limit minimum is less than 1 and is an invalid matplotlib date value

I can't figure out how to change the format of these x-labels. Ideally, I'd like to call strftime('%Y-%m-%d') on them. I've tried things like set_major_formatter but was unsuccessful.

import pandas as pd
import numpy as np
date_range = pd.date_range('2014-01-01', '2015-01-01', freq='MS')
df = pd.DataFrame({'foo': np.random.randint(0, 10, len(date_range))}, index=date_range)
ax = df.plot(kind='bar')

The objects in the date_range DF are Timestamp objects. Call Timestamp.strftime on each object:

date_range = pd.date_range('2014-01-01', '2015-01-01', freq='MS')
date_range = date_range.map(lambda t: t.strftime('%Y-%m-%d'))
print date_range
array([2014-01-01, 2014-02-01, 2014-03-01, 2014-04-01, 2014-05-01,
       2014-06-01, 2014-07-01, 2014-08-01, 2014-09-01, 2014-10-01,
       2014-11-01, 2014-12-01, 2015-01-01], dtype=object)

This allows for more general formatting options versus truncating the ticklabel string.

Pandas & Matplotlib: personalize the date format in a bar chart , He wanted to change the format of the dates on the x-axis in a simple bar chart with data read from a csv We can try to use the option kind='bar' in the pandas plot() function The date labels formatted in this way are ugly! Examples on how to plot data directly from a Pandas dataframe, using matplotlib and pyplot. pyplot as plt import pandas as pd df. plot to datetime: custom

Simply access the tick labels and change them:

xtl=[item.get_text()[:10] for item in ax.get_xticklabels()]
_=ax.set_xticklabels(xtl)

Customize Dates on Time Series Plots in Python Using Matplotlib , Matplotlib allows you to natively plots python datetime instances, and for plt.​subplots() ax.plot(date, r.close) ax.set_title('Default date handling the x locations are formatted the same way the tick labels are, e.g., "Dec 2004". If True, format the number according to the current locale. This affects things such as the character used for the decimal separator. If False, use C-style (English) formatting. The default setting is controlled by the axes.formatter.use_locale rcparam. useMathText: If True, render the offset and scientific notation in mathtext

You could just pass new labels exactly with your preferred strftime:

ax.set_xticklabels([pandas_datetime.strftime("%Y-%m-%d") for pandas_datetime in df.index])

It's not the prettiest answer, but it gets the job done consistently.

Fixing common date annoyances, Make plots of DataFrame using matplotlib / pylab. New in version 0.17.0: Each plot kind has a corresponding method on the DataFrame.plot accessor: df.plot(​kind='line') is equivalent to df.plot.line() . In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if  For a pandas series s the code: fig, ax = plt.subplots() ax.plot(s.index, s) produces a plot in which the x-labels are integer timestamps. With previous versions of pandas, this code would yield string timestamps on the x-axis.

pandas.DataFrame.plot, bmh – based on the style of the book Bayesian Methods for Hackers; classic import datetime import pandas as pd # Some dates dates = ['2017-01-01', import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(df['date'], df['y_values'​]) One of the downsides of plotting dates on the x-axis is that the x-tick labels usually  pandas.DataFrame.plot¶ DataFrame.plot (self, *args, **kwargs) [source] ¶ Make plots of Series or DataFrame. Uses the backend specified by the option plotting.backend. By default, matplotlib is used. Parameters data Series or DataFrame. The object for which the method is called. x label or position, default None. Only used if data is a DataFrame.

Better matplotlib charts, However, bar plot use the FixedFormatter which outputs the datetime as it is. series is set as index, line plot uses the TimeSeries_DateFormatter for recognizable date formatting. FixedFormatter instance at 0x108700f38> In [11]: a = df.plot() In [12]: Using plt.bar instead of pandas Series plot method. matplotlib.pyplot.xticks¶ matplotlib.pyplot.xticks (ticks=None, labels=None, \*\*kwargs) [source] ¶ Get or set the current tick locations and labels of the x-axis. Pass no arguments to return the current values without modifying them.

Using pandas.TimeSeries_DateFormatter in bar plot? · Issue #1918 , Examples on how to plot data directly from a Pandas dataframe, using matplotlib and pyplot. You can plot data directly from your DataFrame using the plot() method: as 'dummy' plt.xlabel('state') # disable ticks in the x axis plt.xticks([]) # fix -date-and-time#string-column-to-date-datetime-custom-format]. Matplotlib date format¶ Matplotlib represents dates using floating point numbers specifying the number of days since 0001-01-01 UTC, plus 1. For example, 0001-01-01, 06:00 is 1.25, not 0.25. Values < 1, i.e. dates before 0001-01-01 UTC, are not supported. There are a number of helper functions to convert between datetime objects and Matplotlib

Comments
  • Thanks! Accepted yours because it let me call strftime and thus allows for more formatting options, as you pointed out