Home >Backend Development >Python Tutorial >How Can I Share X Axes of Matplotlib Subplots After Their Creation?
In matplotlib, subplots created independently have separate x and y axes. To share axes among subplots, it's typically recommended to specify the shared property during subplot creation.
However, this article addresses the specific scenario of sharing x axes after the subplots have already been created. This may arise when using libraries that generate pre-existing subplots.
To link the x axes of two subplots after their creation, use the sharex(ax) method:
<code class="python">ax2.sharex(ax1)</code>
where ax1 is the subplot with the desired x axis, and ax2 is the subplot for which you want to share the x axis.
After sharing the x axes, you need to disable the x tick labels on one of the subplots to avoid duplication.
<code class="python">ax1.set_xticklabels([]) # Disable x tick labels for ax1</code>
Depending on the need, you may want to use the autoscale() method on the second subplot (ax2) to adjust its y-axis scaling.
Consider the following code that creates two subplots and then shares their x axes post-creation:
<code class="python">import numpy as np import matplotlib.pyplot as plt t = np.arange(1000) / 100 x = np.sin(2 * np.pi * 10 * t) y = np.cos(2 * np.pi * 10 * t) fig = plt.figure() ax1 = plt.subplot(211) ax1.plot(t, x) ax2 = plt.subplot(212) ax2.plot(t, y) ax2.sharex(ax1) ax1.set_xticklabels([]) # ax2.autoscale() # Uncomment for autoscaling plt.show()</code>
This code generates two subplots, each with its own y axis but sharing the same x axis. The x tick labels are disabled on the first subplot to avoid duplication. And, if necessary, autoscaling can be applied to the second subplot for y-axis adjustment.
The above is the detailed content of How Can I Share X Axes of Matplotlib Subplots After Their Creation?. For more information, please follow other related articles on the PHP Chinese website!