pythonmatplotlib

xtick labels not showing on python line plot


My Python code of departures vs years, below works fine for a bar plot. I would like to have year tick mark labels on the x-axis. Currently I get the line plot, but no years labelled on the x-axis. For the bar plot the years are labelled alright.

This is not a multi-plot (or subplots), but plotting the line plot while the bar plotting is commented, and vice versa. Why does one work and the other does not?

sample image

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

df = pd.read_csv('../RnOut/RAINFALL/Deps/CHIPAT.txt', sep=' ', skipinitialspace=True )

fig, ax = plt.subplots(figsize=(10, 10))

#Drop rows with missing values
#*****************************
df_new = df.drop(df[df['Dep'] <= -99.].index)

#set xtick labels
#****************
xticks=np.arange(df_new['Year'].iloc[0], df_new['Year'].iloc[-1], 5)
xlabels = [f'{x:d}' for x in xticks]
ax.set_xticks(xticks, labels=xlabels)
plt.xticks(xticks, labels=xlabels)

#Draw line plot
#**************
#df_new['Dep'].plot(ax=ax)

#Draw bar plot, red for negative bars
#************************************
colors = ['g' if e >= 0 else 'r' for e in df_new['Dep']]
plt.bar(df_new['Year'],df_new['Dep'], color=colors,edgecolor='black')

#Set titles
#**********
ax.set_title('Rainfall Departures: Oct-Mar\n ---------------------------------------')
plt.xlabel("Years")
plt.ylabel("Rainfall Departure (Std Dev)")

ax.grid()
plt.savefig('ChipatDep.png')
plt.show()

my sample data

Year  Dep
 1945  -0.9
1946   0.9
1947   0.6
1948  -0.7
1949   1.2
1950  -0.9
1951   0.9
1952   0.1
1953  -1.0
1954   1.3
1955  -0.3

Solution

  • The problem is you are explicitly specifying the Yearcolumn as your x-axis values. But with df_new['Dep'].plot(), you're not specifying` x` values, so it uses the DataFrame index instead.

    ax.plot(df_new['Year'], df_new['Dep'])