[Matplotlib-users] Bug with changing formatter and locator of a secondary axis ?
Pierre Haessig
pierre.haessig at crans.org
Mon Oct 14 11:38:06 EDT 2019
Hello,
I've a question on the secondary axis feature introduced in matplotlib
3.1
<https://matplotlib.org/3.1.1/users/whats_new.html#secondary-x-y-axis-support>.
I'm on version 3.1.1.
My use case is to plot log values but also display the exponentiated
values. I can use a twin axes with the shared scale and a functional
formatter. Here is an example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator, FuncFormatter
fig, ax = plt.subplots(1,1)
# twin ax with shared scale
# cf. @ImportanceOfBeingErnest at
https://stackoverflow.com/questions/55907892/matplotlib-secondary-axis-with-values-mapped-from-primary-axis
ax2 = ax.twiny()
ax.get_shared_x_axes().join(ax, ax2)
# Plot
ax.plot([-1,2,5], [1,2,3], 'd-')
ax.grid()
# x axis labeling
ax.set_xlabel('log2 x-value')
ax2.xaxis.set_major_formatter(FuncFormatter(lambda x,pos:
f"{2**x:.3g}"))
ax2.set_xlabel('x-value');
This twinx/y approach works, but I wanted originally to use the new
secondary axis feature. I see to options for this:
1. use a secondary axes with the log transform
2. use a secondary axes with no transform, and then transform the
display ticks using a FuncFormatter
Option 1 works initially, but breaks when I want to use a LogLocator to
have equally spaced log values:
fig, ax = plt.subplots(1,1)
ax.plot([-1,2,5], [1,2,3], 'd-')
ax2 = ax.secondary_xaxis('top', functions=(lambda x: 2**x, np.log2))
# Place ticks at log equally spaced location [doesn't work]
ax2.xaxis.set_major_locator(LogLocator(2))
Option 2 doesn't work either due. Setting the formatter has no effect
fig, ax = plt.subplots(1,1)
ax.plot([-1,2,5], [1,2,3], 'd-')
ax2 = ax.secondary_xaxis('top')
# Format the log values as exponentiated values [doesn't work]
ax2.xaxis.set_major_formatter(FuncFormatter(lambda x,pos:
f"{2**x:.3g}"))
Is it an expected behavior (or a known bug) that changing the locator
and the formatter of a secondary axis has no effect? Did I miss something?
In the examples
(https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/secondary_axis.html),
there is one example (number 3, with interpolated transforms) which
uses secax.xaxis.set_minor_locator(AutoMinorLocator()), but I don't know
if it is effective or not.
Best,
Pierre
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/matplotlib-users/attachments/20191014/98abae4a/attachment.html>
More information about the Matplotlib-users
mailing list