创建后如何动态共享 Matplotlib 中子图的 x 轴?

DDD
发布: 2024-10-25 05:58:02
原创
578 人浏览过

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

动态共享子图的 X 轴

问题:创建两个子图后共享它们的 x 轴。

解决方案:

共享轴通常是在创建轴时使用 sharex 参数完成的。但是,在已经创建子图的情况下,可以使用 ax2.sharex(ax1) 共享它们的 x 轴。

这里有一个 Python 代码示例来说明这种方法:

<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>
登录后复制

在此代码中,创建子图后,我们使用 ax2.sharex(ax1) 链接两个子图的 x 轴。为了防止重复的刻度标签,我们手动禁用 ax1。

或者,您可以使用循环来共享子图列表的 x 轴,例如:

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

for ax in axes[1:]:
    ax.sharex(axes[0])</code>
登录后复制

以上是创建后如何动态共享 Matplotlib 中子图的 x 轴?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!