Skip to content Skip to sidebar Skip to footer

Why Cannot I Apply Zoom Axes Range To Dual Axis, Like I Can Pan Axes Range, For Interactive Matplotlib Plot?

The below code example is modified from the basis on Matplotlib: Finding out xlim and ylim after zoom Basically, in that example, I want to have a dual x axis; and I want the seco

Solution 1:

Thanks to @ImportanceOfBeingErnest - I think I have an example now, that behaves the way I want - also for differing axes' ranges:

Figure_1

Basically, without a callback, and with setting labels manually, all works as @ImportanceOfBeingErnest mentioned - except, when zooming, the old set of labels will remain (and so, when you zoom in, you might see 10 ticks on the original axis, but only 1 tick on the dual); so here, the callback is just used to "follow" the original axis labels:

#!/usr/bin/env python3import matplotlib
print("matplotlib.__version__ {}".format(matplotlib.__version__))
import matplotlib.pyplot as plt

## Some toy data
x_seq = [x / 100.0for x inrange(1, 100)]
y_seq = [x**2for x in x_seq]

## Scatter plot
fig, ax = plt.subplots(1, 1)
ax.plot(x_seq, y_seq)

# https://stackoverflow.com/questions/31803817/how-to-add-second-x-axis-at-the-bottom-of-the-first-one-in-matplotlib
ax22 = ax.twiny() # instantiate a second axes that shares the same y-axis# Move twinned axis ticks and label from top to bottom
ax22.xaxis.set_ticks_position("bottom")
ax22.xaxis.set_label_position("bottom")
# Offset the twin axis below the host
ax22.spines["bottom"].set_position(("axes", -0.06))

factor = 655
old_xlims = ax.get_xlim()
new_xlims = (factor*old_xlims[0], factor*old_xlims[1])
old_tlocs = ax.get_xticks()
new_tlocs = [i*factor for i in old_tlocs]
print("old_xlims {} new_xlims {} old_tlocs {} new_tlocs {}".format(old_xlims, new_xlims, old_tlocs, new_tlocs))
ax22.set_xticks(new_tlocs)
ax22.set_xlim(*new_xlims)

defon_xlims_change(axes):
  old_tlocs = ax.get_xticks()
  new_tlocs = [i*factor for i in old_tlocs]
  ax22.set_xticks(new_tlocs)

ax.callbacks.connect('xlim_changed', on_xlims_change)

## Show
plt.show()

Post a Comment for "Why Cannot I Apply Zoom Axes Range To Dual Axis, Like I Can Pan Axes Range, For Interactive Matplotlib Plot?"