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?
The issue here is that
.formatlooks 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,xcan be left in the string and will be ignored by the.format. So, to achieve your desired results, you would do: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.
You can also save the formatting to a variable since you will be using it every loop.