How to unset `sharex` or `sharey` from two axes in Matplotlib

nor*_*ok2 6 python matplotlib subplot

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.

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)
Run Code Online (Sandbox Code Playgroud)

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

axs[0, 9].sharex = False
axs[1, 9].sharey = False
Run Code Online (Sandbox Code Playgroud)

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

Imp*_*est 7

正如@zan 在他们的回答中指出的那样,您可以使用ax.get_shared_x_axes()获取一个Grouper包含所有链接轴的对象,然后是.remove来自此 Grouper 的任何轴。问题是(正如@WMiller 指出的那样)所有轴的自动收报机仍然相同。

所以一个人需要

  1. 从石斑鱼上取下轴
  2. 使用相应的新定位器和格式化程序设置新的 Ticker

完整示例

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(3, 4, sharex='row', sharey='row', squeeze=False)

data = np.random.rand(20, 2, 10)

for ax in axes.flatten()[:-1]:
    ax.plot(*np.random.randn(2,10), marker="o", ls="")



# Now remove axes[1,5] from the grouper for xaxis
axes[2,3].get_shared_x_axes().remove(axes[2,3])

# Create and assign new ticker
xticker = matplotlib.axis.Ticker()
axes[2,3].xaxis.major = xticker

# The new ticker needs new locator and formatters
xloc = matplotlib.ticker.AutoLocator()
xfmt = matplotlib.ticker.ScalarFormatter()

axes[2,3].xaxis.set_major_locator(xloc)
axes[2,3].xaxis.set_major_formatter(xfmt)

# Now plot to the "ungrouped" axes
axes[2,3].plot(np.random.randn(10)*100+100, np.linspace(-3,3,10), 
                marker="o", ls="", color="red")

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

请注意,在上面我只更改了 x 轴的代码,也只更改了主要的刻度。如果需要,您需要对 y 轴和次要刻度执行相同的操作。


zan*_*zan 4

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

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()
Run Code Online (Sandbox Code Playgroud)

这仍然需要一些调整来设置刻度,但右下角的图现在有其自己的限制。 不共享轴