I am trying to plot some time series’ and I struggle with the tick labels. my df looks like this:
Q1-Q5 Date 2003 -0.183333 2004 -0.195833 2005 0.044167 2006 -0.040000 2007 0.841667 2008 0.251667 2009 -0.913333 2010 -0.471667 2011 0.005833 2012 -0.297500 2013 -0.625833 2014 0.290833 2015 0.059167 2016 0.632500 2017 1.015000 2018 0.258333 2019 0.030000 2020 0.651667 2021 0.255000
The code to plot it looks like this:
fig, (ax1, ax2,ax3, ax4) = plt.subplots(4, 1, figsize = (20,20)) df.plot(ax = ax1) ax1.set_yticks(y_ticks) ax1.tick_params(axis='x', labelrotation = 90) ax1.grid(axis = 'y') ax1.set_ylim(-1.5, 1.5)
The plot however looks like this
https://i.stack.imgur.com/tKqP6.png
How can I make it thath it shows all years as x ticks?
Thank you in advance
Advertisement
Answer
Try this:
import pandas as pd import matplotlib.pylab as plt data = pd.read_csv("years_data.txt", sep=" ") fig, (ax1, ax2,ax3, ax4) = plt.subplots(4, 1, figsize = (20,20)) data.plot(x='Year', y='Q1-Q5', ax = ax1) ax1.set_xticklabels(data['Year']) ax1.grid(axis = 'y') ax1.set_ylim(-1.5, 1.5)
I used set_xticklabels()
function instead of tick_params()
. I found this tutorial here. You have to give it the list of tick marks that you desire.
If you want to see only the plot of interest:
fig, ax =plt.subplots() data.plot(x='Year', y='Q1-Q5', ax =ax) ax.set_xticklabels(data['Year']) ax.set_ylim(-1.5, 1.5)
The output:
Then I personally like to modify tick marks using the function plt.setp()
:
fig, ax =plt.subplots() data.plot(x='Year', y='Q1-Q5', ax =ax) ax.set_xticklabels(data['Year']) plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45, ha="left", weight="bold") ax.set_ylim(-1.5, 1.5)
The output is: