Issue
I am writing a function to format the tick labels on the y axis. The scale is logarithmic, so the unformatted axes looks like this:
I want the labels to be 10^-1, 10^-2, etc. but with the power shown as superscript.
This is the function I am using now:
from matplotlib.ticker import FormatStrFormatter
fmt = lambda x, pos: '$10^{:.0f}$'.format(x, pos)
ax3 = fig.add_subplot()
ax3.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt))
However, this results in the minus being a superscript, but the number a normal character (see below). How do I fix that? I tried to make the x negative in the function and add the minus in the curly brackets but that doesn't seem to work either.
Solution
You need to put double braces around the exponent, otherwise only the first character will be superscript:
from matplotlib.ticker import FuncFormatter
fmt = lambda x, pos: f'$10^{{{x:.0f}}}$'
fig, ax = plt.subplots()
ax.set_ylim((-6, -1))
ax.yaxis.set_major_formatter(FuncFormatter(fmt))
You can also directly pass the formatting string instead of a formatter, in which case a StrMethodFormatter
will be created under the hood. See set_major_formatter
.
ax.yaxis.set_major_formatter('$10^{{{x:.0f}}}$')
Answered By - Stef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.