2

I have resampled data from a monthly series to plot the yearly mean value. However, the year ticks show up in the following format in the X axis:

Correct plot

However, I want only the years to be shown, not the entire timestamp. But the following code does not plot the graph correctly.

ax = umtmvsDF.resample('A').mean().plot.bar(title='Average value per year',grid=True,color=(.21,.42,.12),figsize=(12,10))
    ax.set(xlabel=Constants.TIME,ylabel=Constants.USD)
    ax.xaxis.set_major_formatter(dates.DateFormatter('%Y'))
    plt.show() 

Incorrect plot

This code shows all the ticks to be equal to 1970. What am I doing wrong here?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Zer0
  • 39
  • 5

2 Answers2

1

As an alternative, this might work for you:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

umtmvsDF = pd.Series(
    data = np.random.randint(0, high=100, size=132, dtype=int), 
    index = pd.date_range(start='1/1/1980', end='1/1/1991', freq='M')
)

df = umtmvsDF.resample('A').mean()

ax = df.plot.bar(
    title = 'Average value per year',
    grid = True,
    color = (.21,.42,.12),
    figsize = (12,10)
)

ax.set_xticklabels(df.index.strftime('%Y'))

plt.show()

enter image description here

See also the answer to this question.

René
  • 4,594
  • 5
  • 23
  • 52
  • While I didn't create a series, I did follow the method in the link you shared. The data format was as per my expectation. Thanks. I've updated my query with the solution. – Zer0 May 26 '21 at 11:14
0

@René shared the link which finally solved the question. It provides the reason 1970 showed up in the 2nd graph.

Revised code

tempDF3 = umtmvsDF.resample ( 'A' ).mean ()
ax = tempDF3.plot.bar ( title='Average value per year', grid=True, color=(.21, .42, .12),
                                                  figsize=(12, 10) )
ax.set ( xlabel=Constants.TIME, ylabel=Constants.USD )

ticklabels = ['']*len(tempDF3.index)
ticklabels[::5] = [item.strftime('%Y') for item in tempDF3.index[::5]]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.gcf().autofmt_xdate()
plt.show ()

Solution graph:

enter image description here


This answer was posted as an edit to the question Unable to format X ticks in Pandas after resampling by the OP Zer0 under CC BY-SA 4.0.

vvvvv
  • 25,404
  • 19
  • 49
  • 81