Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

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

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)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @zan points out in the their answer, you can use ax.get_shared_x_axes() to obtain a Grouper object that contains all the linked axes, and then .remove any axes from this Grouper. The problem is (as @WMiller points out) that the ticker is still the same for all axes.

So one will need to

  1. remove the axes from the grouper
  2. set a new Ticker with the respective new locator and formatter

Complete example

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

Note that in the above I only changed the ticker for the x axis and also only for the major ticks. You would need to do the same for the y axis and also for minor ticks in case it's needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...