0

I´m trying to simplify my script using more indices for array; however, always get an IndexError. This is part of my script:

# Set the values in x-axis, only for the first plot
axs[0].set_xlim(0, 1200)
axs[0].set_ylim(-800, 200)
# Set the range of values in x-axis
axs[0].xaxis.set_major_locator(MultipleLocator(50))
# Set the values in y-axis, only for the rest
axs[1].set_xlim(0, 1200)
axs[1].set_ylim(0, 9)
axs[2].set_xlim(0, 1200)
axs[2].set_ylim(0, 9)

Well, I think that these lines could be more simplified. For example, using:

axs[1,2].set_ylim(0, 9)

Where the y-axis has the range 0-9; however, when I tried to made that I have the error:

IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

I understand the error partially; however, my question for this post is:

Is there a way to fix that problem to use in one line the ...[1,2]set_ylim...? Or there is no way to do that?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Mauri1313
  • 345
  • 4
  • 12
  • What is `type(axs)`? – Pranav Hosangadi Jun 23 '21 at 14:55
  • Thank you for the anwer. It´s a `numpy.ndarray` Any idea of what to do? – Mauri1313 Jun 23 '21 at 14:56
  • 1
    Does this answer your question? [How to get the values from a NumPy array using multiple indices](https://stackoverflow.com/questions/14162026/how-to-get-the-values-from-a-numpy-array-using-multiple-indices) You're still going to have to [`map()` the `set_ylim()` function to all results in the sliced array though](https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array) – Pranav Hosangadi Jun 23 '21 at 14:57
  • I going to look at that post, I´m a beginner using matplotlip. I´m using the `numpy.ndarray` with this line: `fig, axs = plt.subplots(3, 1, sharex=False, figsize=(15, 8))` It´s possible to use multiple indices with that? Sorry for the basic question. – Mauri1313 Jun 23 '21 at 15:01

1 Answers1

2

You may look toward this:

def set_ylims(indices: list, vals: tuple):
    for i in indices: # For each passed index
        axs[i].set_ylim(*vals)  # Unpack vals and call set_ylim()

For example:

my_indices = [2,5,8]
set_ylims(my_indices, (0,9))

Just in case, if you're intimidated my the indices: list part. It's a type hint, in here, it is just to provide clarity. For more, check the documentation.

rawrex
  • 4,044
  • 2
  • 8
  • 24
  • I suppuse that with `axs[i].set_ylim(*vals)` in *vals I must set the values 0.9, am I correct? – Mauri1313 Jun 23 '21 at 15:03
  • 1
    @Mauri1313 yes. We may set the `set_ylims` to have two separate paramaters: `set_ylims(indices, a, b)` and then use them like here: `axs[i].set_ylim(a, b)`. You can choosse whatever is most appropriate in your program. – rawrex Jun 23 '21 at 15:05
  • Great, thank you. I´m a beginner using matplotlip and python, anyway. Have a nice day! – Mauri1313 Jun 23 '21 at 15:07