1

Currently my y-axis ticks all have the same number of digits after the decimal point, so the total length of the ticks is different. I want the total lengths of tick-digits to be the same. How can I do this?

My code is as follows:

ax = plt.gca()
ax.yaxis.set_major_formatter(FormatStrFormatter('%1.3f'))

Here the y-axis ticks have different total lengths:

I want the total lengths of tick-digits to be the same:

y-axis ticks has the same lengths

tdy
  • 36,675
  • 19
  • 86
  • 83
EverChyi
  • 13
  • 2
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 21 '23 at 15:58

1 Answers1

0

Use FuncFormatter() instead.

from matplotlib.ticker import FuncFormatter
import math

Create a function outputting the desired label:

def my_format(val, pos):

    n = 3
    y = abs(val)

    dec = max(0,
              min(n,n-int(math.log10(y)))) if y else n

    return f"{val:.{dec}f}"

*(dec adapted from the accepted answer in Format float with fixed amount of digits python)

Apply the function to your axis, instead of the FormatStrFormatter():

ax.yaxis.set_major_formatter(FuncFormatter(my_format))
fdireito
  • 1,709
  • 1
  • 13
  • 19
  • Note that the two argument formulation of my_format() is required by FuncFormatter(), even though we only use the first one. – fdireito Feb 21 '23 at 16:23