1

I want to use setattr to create a plot:

    import numpy as np
    import matplotlib.pyplot as plt

    x = np.random.rand(10)
    y = np.random.rand(10)

    # I want this:
    # plt.scatter(x, y)
    setattr(plt, "scatter", [HOW TO PASS X AND Y])

Since value I want to pass is not single, how should I do it? Basically, this should be the result: plt.scatter(x, y)

Alec
  • 8,529
  • 8
  • 37
  • 63
ivanacorovic
  • 2,669
  • 4
  • 30
  • 46

2 Answers2

2

I think what you are looking for is getattr. In this case, it will return a Callable, so you can just treat it like a function, like this:

getattr(plt, 'scatter')(x, y)

Is the same as this:

plt.scatter(x, y)

Using setattr in that way would be more akin to plt.scatter = (x, y), which I don't think is what you want to do.

gmds
  • 19,325
  • 4
  • 32
  • 58
1

You're not setting an attribute, but instead calling one.

getattr(plt, some_func)(x, y)

will call

plt.some_func(x, y)

So, in your case, you want to run

getattr(plt, 'scatter')(x, y)
Alec
  • 8,529
  • 8
  • 37
  • 63