Home > Software design >  Get ylimits and xlimits of matplotlib subplot
Get ylimits and xlimits of matplotlib subplot

Time:12-07

I'm trying to get the ylim of matplotlib subplot. I want to get the range i.e. xlim and ylim of each row.

import matplotlib.pyplot as plt
fig1, fig1_axs = plt.subplots(
            nrows=5, ncols=3,
            figsize=(18, 20),
        )
....
plt.getp(fig1_axs[1, :], 'ylim')

but this returns the following error

AttributeError: 'numpy.ndarray' object has no attribute 'get_ylim'

I basically want to get the ylim of each row i.e. max value and set the ymax to all the columns in the same row.

Suggestions will be really helpful.

CodePudding user response:

Well, as the error is saying fig1_axs[1, :] is a numpy array, and numpy arrays do not have an attribute 'get_ylim', which is what getp tries to apply to it's first argument.

matplotlib.pyplot.getp works only on individual matplotlib artists, so you'll need to iterate over each axes in the row and determine the max value. Then iterate over them again to set the limits.

max_y = -float('inf') # Choose a big number of inf
row = fig1_axs[1, :]
for ax in row:
    y = plt.getp(ax, 'ylim')
    if y[1] > max_y: 
        max_y = y[1]
  • Related