如何从Matplotlib中的两个轴取消设置“sharex”或“sharey”

2024-10-01 00:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的子批次,我希望它们在除了2个子批次之外的所有子批次中共享x和y轴(以每行为基础)。在

我知道可以单独创建所有子批次,然后add the ^{}/^{} functionality afterward。在

但是,这是一个非常多的代码,因为我必须对大多数子批执行此操作。在

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

import matplotlib.pyplot as plt

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

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

^{pr2}$

上面的方法不起作用,但是有什么方法可以得到它吗?在


Tags: the方法代码importadd属性matplotlibplt
3条回答

正如@zan在their answer中指出的那样,您可以使用ax.get_shared_x_axes()获得一个Grouper对象,它包含所有链接的轴,然后.remove来自这个分组程序的任何轴。问题是(正如@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()

enter image description here

注意,在上面我只改变了x轴的记号,也只改变了主刻度。如果需要的话,对y轴和小记号也需要执行相同的操作。在

您可以使用ax.get_shared_x_axes()或属性ax._shared_y_axes访问共享轴组。然后可以使用xaxis.set_tick_params(which='both', labelleft=True)或使用setp(ax, get_xticklabels(), visible=True)重置标签的可见性,但是这两种方法都有一个固有的问题:记号格式化程序仍然在轴之间共享。据我所知,这是没有办法的。下面是一个示例来演示:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
fig, axs = plt.subplots(2, 2, sharex='row', sharey='row', squeeze=False)
axs[0][0]._shared_x_axes.remove(axs[0][0])
axs[0][0]._shared_y_axes.remove(axs[0][0])

for ii in range(2):
    for jj in range(2):
        axs[ii][jj].plot(np.random.randn(100), np.linspace(0,ii+jj+1, 100))

axs[0][1].yaxis.set_tick_params(which='both', labelleft=True)
axs[0][1].set_yticks(np.linspace(0,2,7))
plt.show()

Unsetting shared axis

您可以使用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()

这仍然需要一些调整来设置记号,但是右下角的绘图现在有了自己的限制。 unshared axes

相关问题 更多 >