I am not really a python guy. I am coming from Fortran background and trying to understand object-oriented programming, so please forgive me if my questions are silly! I have the following simple piece of code:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(6,6))
ax1 = fig.add_axes([0.1,0.1,0.6,0.6])
a = ax1
ya = 'yaxis'
x = np.linspace(0.0, 2.*np.pi)
a.ya.set_ticks_position('left')
a.plot(x,np.sin(x))
plt.show()
Now I want to assign a variable ya
the axes attribute yaxis
. Obviously 'yaxis'
is string so ya
will be a string variable.
So, my code fails with:
Traceback (most recent call last):
File "./t.py", line 14, in <module>
a.ya.set_ticks_position('left')
AttributeError: 'Axes' object has no attribute 'ya'
I see the reason for this (because ya
is a string variable and a
is a class object and expects an attribute of some data type). My questions is how do you convert the ya = yaxis
to a proper variable that a
or ax1
will accept. I know in this case it is sort of redundant doing it but eventually I will be looping over many axes and their attributes e.g. (ax1, ax2.......)
and xaxis, yaxis
and I don't want to have them hard coded.
Any help will be very much appreciated!
Check the built-in functions getattr
and setattr
.
getattr(object, attrname)
setattr(object, attrname, value)