Home > Software design >  How to remove all y-axis tick labels and markers except for '0' in a matplotlib subplot?
How to remove all y-axis tick labels and markers except for '0' in a matplotlib subplot?

Time:07-18

The code:

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

fig, axs = plt.subplots(2, sharex = True, figsize=(9,6),dpi=500, 
                    gridspec_kw={'height_ratios': [3, 1]})    

axs[0].set_title("Smoothed Kalman Point Estimate Fit to "   symbol)
axs[0].plot(dates, price_series, c='black', linestyle = '-', linewidth = 2)
axs[0].plot(dates, kf_point_est, c='yellow', linestyle = '-', linewidth = 1)
axs[0].xaxis.set_major_formatter(DateFormatter("%y"))
axs[0].margins(x=0)

axs[1].set_title("Slope")
axs[1].plot(dates, pos_slope, color='g')
axs[1].plot(dates, neg_slope, color='r')
axs[1].axhline(0, c='black', linestyle = '--', linewidth = 1)
axs[1].xaxis.set_major_formatter(DateFormatter("'%y"))
axs[1].margins(x=0)

Which produces the following plot:

enter image description here

But I want to remove all y-axis tick labels (and tick markers) apart from if tick label = 0, so that it looks like this:

enter image description here

I understand I only have one other y-axis tick, but I need the code to be robust to handle any amount of tick markers/labels.

Also, I would like to round the remaining 0 to have no decimal places. so it reads "0" as opposed to "0.0000".

CodePudding user response:

If I understand correctly you could do this in one line like

axs[1].yaxis.set_ticks([0])

It should be formatted as 0, because I am passing an integer.

  • Related