How do I dynamically share the x-axis of subplots in Matplotlib after creation?

DDD
Release: 2024-10-25 05:58:02
Original
578 people have browsed it

How do I dynamically share the x-axis of subplots in Matplotlib after creation?

Sharing X Axes of Subplots Dynamically

Problem: Sharing the x-axes of two subplots after they have been created.

Solution:

Sharing axes is typically done during their creation using the sharex parameter. However, in cases where subplots have already been created, it's possible to share their x-axes using ax2.sharex(ax1).

Here's a Python code example to illustrate this approach:

<code class="python">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)  # Create subplot 1
ax2 = plt.subplot(212)  # Create subplot 2

# Plot data in the subplots
ax1.plot(t, x)
ax2.plot(t, y)

# Share the x-axes between the subplots
ax2.sharex(ax1)

# Disable tick labels for one of the subplots to avoid duplication
ax1.set_xticklabels([])

plt.show()</code>
Copy after login

In this code, after creating the subplots, we use ax2.sharex(ax1) to link the x-axes of the two subplots. To prevent duplicate tick labels, we manually disable them for ax1.

Alternatively, you can use a loop to share x-axes for a list of subplots, such as:

<code class="python">axes = [ax1, ax2, ax3]

for ax in axes[1:]:
    ax.sharex(axes[0])</code>
Copy after login

The above is the detailed content of How do I dynamically share the x-axis of subplots in Matplotlib after creation?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!