Home  >  Article  >  Backend Development  >  How to Share X-Axes of Matplotlib Subplots After Creation?

How to Share X-Axes of Matplotlib Subplots After Creation?

DDD
DDDOriginal
2024-10-25 03:05:30315browse

How to Share X-Axes of Matplotlib Subplots After Creation?

Sharing X Axes of Subplots Post-Creation

When creating subplots, it is ideal to establish shared axes properties at the time of creation using sharex argument. However, there may be instances where you need to share axes after the subplots have been generated.

To share the x axis of two subplots after their creation, use the ax2.sharex(ax1) function. This establishes a link between the two axes named ax1 and ax2, enabling them to share the same x axis.

In this scenario, you will need to manually set the xticklabels for one of the axes if desired. For example:

<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)
plt.plot(t,x)

ax2 = plt.subplot(212)
plt.plot(t,y)

ax2.sharex(ax1)
ax1.set_xticklabels([])  # Disable xticklabels for ax1

plt.show()</code>

The above code creates two subplots with shared x axis. The xticklabels are only visible on the top subplot, while the bottom subplot is left without xticklabels.

For a list of axes, you can use the following code to share the x axis with the first axis:

<code class="python">for ax in axes[1:]:
    ax.sharex(axes[0])</code>

The above is the detailed content of How to Share X-Axes of Matplotlib Subplots After Creation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn