0

I need to dynamically change plot properties based on an input where the user selects the property they want to change and enters the value they want to change it to. I thought I could accomplish this by performing the following:

Selected_Property is a plot parameter (e.g., xscale ect..)
Entered_Value is whatever the user wants to change the value to
    
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [1, 10, 100, 1000, 10000, 100000]
plt.plot(x,y)
setattr(plt, Selected_Property, Entered_Value)
plt.show()

However, no matter what I put in setattr, no changes are applied to the plot. I cannot change plot properties using plt.(property to change) because this property is selected dynamically based on the user's input and I do not know how to access plot properties using variables and "." notation. Is there anything I can try to fix this issue?

Gaven
  • 953
  • 2
  • 8
  • 14

1 Answers1

1

You can do it like this:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [1, 10, 100, 1000, 10000, 100000]
plt.plot(x,y)
getattr(plt, 'xlabel')('myplot')
plt.show()

Output:

enter image description here

David M.
  • 4,518
  • 2
  • 20
  • 25
  • David, thanks so much, that is exactly what I needed! By any chance, do you know why setattr in my code above did not work? If not no worries, your solution above worked perfectly – Gaven Mar 05 '21 at 20:33
  • As `plt` is a module, it [is not callable](https://stackoverflow.com/q/111234/1453508) so you cannot use `setattr`. Conversely, `getattr` [returns a callable](https://stackoverflow.com/a/56248673/1453508) which you can use to assign values to properties. – David M. Mar 05 '21 at 21:45