8000 Add examples · matplotlib/matplotlib@cb55d34 · GitHub
[go: up one dir, main page]

Skip to content

Commit cb55d34

Browse files
Add examples
1 parent b03e3b7 commit cb55d34

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

galleries/examples/subplots_axes_and_figures/secondary_axis.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,26 @@ def rad2deg(x):
4040
secax.set_xlabel('angle [rad]')
4141
plt.show()
4242

43+
# %%
44+
# Normally, secondary axes are placed at either the 'top' or 'bottom'
45+
# of the plot. We can also pass a custom transform to the axis and
46+
# draw it relative to that transform. Here, we draw an axis at Y = 0
47+
# in our data.
48+
49+
fig, ax = plt.subplots(layout='constrained')
50+
x = np.arange(0, 10)
51+
np.random.seed(34)
52+
y = np.random.randn(len(x))
53+
ax.plot(x, y)
54+
ax.set_xlabel('X')
55+
ax.set_ylabel('Y')
56+
ax.set_title('Random data')
57+
58+
# Pass ax.transData as a transform to place the axis relative to our data
59+
secax = ax.secondary_xaxis(0, transform=ax.transData)
60+
secax.set_xlabel('Axis at Y = 0')
61+
plt.show()
62+
4363
# %%
4464
# Here is the case of converting from wavenumber to wavelength in a
4565
# log-log scale.

lib/matplotlib/axes/_axes.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -581,6 +581,18 @@ def invert(x):
581581
secax = ax.secondary_xaxis('top', functions=(invert, invert))
582582
secax.set_xlabel('Period [s]')
583583
plt.show()
584+
585+
To add a secondary axis relative to your data, you can pass a transform
586+
to the new axis.
587+
588+
.. plot::
589+
590+
fig, ax = plt.subplots()
591+
ax.plot(range(0, 5), range(-1, 4))
592+
593+
# Pass 'ax.transData' as a transform to place the axis
594+
# relative to your data at y=0
595+
secax = ax.secondary_xaxis(0, transform=ax.transData)
584596
"""
585597
if not (location in ['top', 'bottom'] or isinstance(location, Real)):
586598
raise ValueError('secondary_xaxis location must be either '

0 commit comments

Comments
 (0)
0