本文介绍了如何在Matplotlib中从两个轴取消设置`sharex`或`sharey`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列子图,我希望它们在2个子图中共享x和y轴(按行).

I have a series of subplots, and I want them to share x and y axis in all but 2 subplots (on a per-row basis).

我知道可以单独创建所有子图,然后.

I know that it is possible to create all subplots separately and then add the sharex/sharey functionality afterward.

但是,鉴于我必须对大多数子图执行此操作,因此这是很多代码.

However, this is a lot of code, given that I have to do this for most subplots.

一种更有效的方法是创建具有所需sharex/sharey属性的所有子图,例如:

A more efficient way would be to create all subplots with the desired sharex/sharey properties, e.g.:

import matplotlib.pyplot as plt

fix, axs = plt.subplots(2, 10, sharex='row', sharey='row', squeeze=False)

,然后设置 unset sharex/sharey功能,假设地的工作方式如下:

and then set unset the sharex/sharey functionality, which could hypothetically work like:

axs[0, 9].sharex = False
axs[1, 9].sharey = False

上面的方法不起作用,但是有什么方法可以做到这一点?

The above does not work, but is there any way to obtain this?

推荐答案

您可以使用ax.get_shared_x_axes()获取包含所有链接轴的Grouper对象.然后使用group.remove(ax)从该组中删除指定的轴.您还可以group.join(ax1, ax2)添加新共享.

You can use ax.get_shared_x_axes() to get a Grouper object that contains all the linked axes. Then use group.remove(ax) to remove the specified axis from that group. You can also group.join(ax1, ax2) to add a new share.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 10, sharex='row', sharey='row', squeeze=False)

data = np.random.rand(20, 2, 10)
for row in [0,1]:
    for col in range(10):
        n = col*(row+1)
        ax[row, col].plot(data[n,0], data[n,1], '.')

a19 = ax[1,9]

shax = a19.get_shared_x_axes()
shay = a19.get_shared_y_axes()
shax.remove(a19)
shay.remove(a19)

a19.clear()
d19 = data[-1] * 5
a19.plot(d19[0], d19[1], 'r.')

plt.show()

这仍然需要一些调整来设置刻度,但是右下图现在有其自身的局限性.

This still needs a little tweaking to set the ticks, but the bottom-right plot now has its own limits.

这篇关于如何在Matplotlib中从两个轴取消设置`sharex`或`sharey`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:54