Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - plotting autoscaled subplots with fixed limits in matplotlib

What's the best way in matplotlib to make a series of subplots that all have the same X and Y scales, but where these are computed based on the min/max ranges of the subplot with the most extreme data? E.g. if you have a series of histograms you want to plot:

# my_data is a list of lists
for n, data in enumerate(my_data):
  # data is to be histogram plotted
  subplot(numplots, 1, n+1)
  # make histogram
  hist(data, bins=10)

Each histogram will then have different ranges/ticks for the X and Y axis. I'd like these to be all the same and set based on the most extreme histogram limits of the histograms plotted. One clunky way to do it is to record the min/max of X/Y axes for each plot, and then iterate through each subplot once they're plotted and just their axes after they're plotted, but there must be a better way in matplotlib.

Can this be achieved by some variant of axes sharing perhaps?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Matplotlib/Pyplot: How to zoom subplots together?

http://matplotlib.org/examples/pylab_examples/shared_axis_demo.html

http://matplotlib.org/users/recipes.html

quoting the last link:

Fernando Perez has provided a nice top level method to create in subplots() (note the “s” at the end) everything at once, and turn off x and y sharing for the whole bunch. You can either unpack the axes individually:

# new style method 1; unpack the axes
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax1.plot(x)

or get them back as a numrows x numcolumns object array which supports numpy indexing:

# new style method 2; use an axes array
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
axs[0,0].plot(x)

If you have an old version of matplotlib the following method should work (also quoting from the last link)

Easily creating subplots In early versions of matplotlib, if you wanted to use the pythonic API and create a figure instance and from that create a grid of subplots, possibly with shared axes, it involved a fair amount of boilerplate code. Eg

# old style
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(223, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(224, sharex=ax1, sharey=ax1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...