1

I am trying to set the x ticks of my axes subplot but it is not working for me. Right now I have the following data frame:

Data Frame

I am using the following code to plot this:

ax=predictions.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4), 
                 legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
ax

And the result is as follows:

Plot

As you can see the month of August is written as Aug 2021. I would like to be able to change all the x ticks to either only the month or the month with the year (e.g keep Jul or set Jul 2021)

I have been trying using ax.set_xticks , but it hasn't work for me so far.

Thanks in advance!

MIGB91
  • 13
  • 3

1 Answers1

0

Don't save the predictions.plot() output into ax. You will simply get a list of lines. After implementing the solution below, you can view the output using plt.show().

When dealing with dates that are datetime objects

For labels with 'Jul 2021', 'Aug 2021', etc, use

import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object

# Please note that df is a DataFrame object. Substitute your DataFrame object's name below. 
dates_index = df.index 

# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{date.strftime("%b")} {date.strftime("%Y")}' for date in dates_index]
print(labels)

plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4), 
                 legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot

For labels with 'Jul 21', 'Aug 21', etc, use

import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object

# Please note that df is a DataFrame object. Substitute your DataFrame object's name below. 
dates_index = df.index

# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{date.strftime("%b")} {date.strftime("%y")}' for date in dates_index]
print(labels)

plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4), 
                 legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot

For labels with 'Jul', 'Aug', etc, use

import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object

# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index 

# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{date.strftime("%b")}' for date in dates_index]
print(labels)

plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4), 
                 legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot

When dealing with dates that are str objects

For labels with 'Jul 2021', 'Aug 2021', etc, use

import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object

# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index

# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{(datetime.datetime.strptime(date, "%Y-%m-%d")).strftime("%b")} {datetime.datetime.strptime(date, "%Y-%m-%d").year}' for date in dates_index]
print(labels)

plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4), 
                 legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot

For labels with 'Jul 21', 'Aug 21', etc, use

import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object

# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index 

# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{(datetime.datetime.strptime(date, "%Y-%m-%d")).strftime("%b")} {datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%y")}' for date in dates_index]
print(labels)

plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4), 
                 legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot

For labels with 'Jul', 'Aug', etc, use

import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object

# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index 

# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{(datetime.datetime.strptime(date, "%Y-%m-%d")).strftime("%b")}' for date in dates_index]
print(labels)

plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4), 
                 legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot
Lihka_nonem
  • 352
  • 1
  • 8
  • Thanks for the answer. The problem with your solution is that I have to set my index as a column to make it work (Date is index not a column in my data frame). I end up doing the following `predictions['Months']=['Jul','Aug','Sep','Oct','Nov','Dec'] predictions.set_index('Months',inplace=True,drop=True)` – MIGB91 May 01 '22 at 14:30
  • I have edited the code to account for the index. Your approach to solving this is not ideal as you are hard-coding the mapping. If I were to put an extra date in between with a month that is not in the order that you have specified, your code will break. – Lihka_nonem May 02 '22 at 09:57
  • Thanks for the answer, but your solution is still not working. I am getting the following error: `TypeError: strptime() argument 1 must be str, not Timestamp`. This is because my index is with format datetime 64ns and not str. – MIGB91 May 02 '22 at 13:28
  • If your index is of type datetime, then you can ignore the strptime() and directly use the strftime() part. The strptime() part is there only to cast the str object into datetime. Please read the documentation on strftime() to get an idea on how this can be done. If you’re still having trouble, I’ll edit the answer once I’m back home. – Lihka_nonem May 02 '22 at 13:33
  • Using your updated code it throws me the same error I used to have: `AttributeError: 'DataFrame' object has no attribute 'xticks'`. Given that we are using AxesSubplot, apparently we are not allow to call xticks. – MIGB91 May 02 '22 at 15:16
  • Yes. A `DataFrame` object will not have the `xticks` attribute. A `matplotlib.pylot` object is what you should be using for plotting and setting the `xticks`. From your code, I gathered that `predictions` was a `matplotlib.pyplot` object. If it is not, please make sure that you make that change and that you use a different variable name for your `DataFrame` object . I will be editing the answer and adding the code using my own `matplotlib.pyplot` object. – Lihka_nonem May 02 '22 at 15:47
  • I have edited the answer. I hope the comments in the code clarify the difference between the `matplotlib.pyplot` and `DataFrame` object. – Lihka_nonem May 02 '22 at 15:59