1

I have an np.array of objects and I want to apply the same method to each object in this array. For example:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2,)

now I want gridlines in every axes object. I know I can do this by iterating over the ax array with an for-loop.

for i in ax:
    i.grid()

Is there a more elegant method? Like np.somefunction(array, method).

Ivan
  • 34,531
  • 8
  • 55
  • 100
l_MP_l
  • 23
  • 4
  • This helps a lot in this special case, but in a general case where you have an array of objects you cannot do that. But thanks for your help – l_MP_l Aug 27 '21 at 15:36
  • I suppose it really depends on what type of objects you are dealing with. – norie Aug 27 '21 at 15:45
  • 2
    An object dtype array is more like a list of objects than a numeric array. So iteration or list comprehension is usually just as good. There is a `np.frompyfunc` function that can make such a call 'prettier', but doesn't change the speed much. – hpaulj Aug 27 '21 at 15:47

1 Answers1

1

If you are using matplotlib, plt.setp would normally be an option to set properties on multiple axes at the same time. Setting the grid is one thing you can't do with setp unfortunately (e.g., matplotlib: why does setting grid with pyplot.setp() causes error?). Instead, you can modify mpl.rcParams. You can do this temporarily for your figure using mpl.rc_context:

from matplotlib import pyplot as plt, rc_context

with rc_context(rc={"axes.grid": True}:
    fig, ax = plt.subplots(2, 2)
fig, ax = plt.subplots(2, 2)

The figures in the context manager looks like this:

enter image description here

The other, like this:

enter image description here

If you are looking for a general purpose method for applying a function to your array, well, there isn't really one: Most efficient way to map function over numpy array.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264