Use .format() with StrMethodFormatter in Matplotlib?

177 views Asked by At

This works:

for ax in fig.axes:
    ax.xaxis.set_major_formatter(StrMethodFormatter("{x:,.3f}"))

This returns KeyError: 'x':

for ax in fig.axes:
        ax.xaxis.set_major_formatter(StrMethodFormatter("{x:,.{}f}".format(3)))

I want to set the number of decimal places in my labels but don't want to hard code how many.

My approach inspired by this answer.

Updates on attempts:

This also works:

`ax.xaxis.set_major_formatter(StrMethodFormatter('{}'.format('{x:,.0f}'))) # No decimal places`

This doesn't, which is confusing:

ax.xaxis.set_major_formatter(StrMethodFormatter('{}'.format('{x:,.{}f}'.format('0') ) ) )

This doesn't, which is also confusing:

x = '{x:,.{}f}'.format(str(0))
ax.xaxis.set_major_formatter(StrMethodFormatter('{}'.format(x) ))

Tried this 'just because', it did not work:

ax.xaxis.set_major_formatter(StrMethodFormatter('{}'.format('{x:,{}}'.format('.0f') ) ) )

What can I try next?

1

There are 1 answers

0
jared On BEST ANSWER

The issue here is that .format looks for curly brackets for replacement. Since you have curly brackets around everything, it gets confused. If you want to have curly brackets in a format string, then you need to double them up. With that change, x can be left in the string and will be ignored by the .format. So, to achieve your desired results, you would do:

precision = 3
for ax in fig.axes:
    ax.xaxis.set_major_formatter(StrMethodFormatter("{{x:,.{}f}}".format(precision)))

If you're using Python 3.6+, then I prefer to use f-strings. Again, you need to double up the curly brackets that are not part of the replacement.

precision = 3
for ax in fig.axes:
    ax.xaxis.set_major_formatter(StrMethodFormatter(f"{{x:,.{precision}f}}"))

You can also save the formatting to a variable since you will be using it every loop.

precision = 3
formatting = f"{{x:,.{precision}f}}"
for ax in fig.axes:
    ax.xaxis.set_major_formatter(StrMethodFormatter(formatting))