Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib get all axes that a given figure contains to apply some settings

I'm writing a function that modifies the axes size and position on a figure, but when comes twin axes it makes a problem:

import matplotlib.pyplot as plt

def fig_layout(fig, vspace = 0.3):  #  function to make space at the bottom for legend box and
                                    #+ other text input
    for ax in ~~~fig.axes~~~: #  Here 'fig.axes' is not right, I need to find the exact syntax
                              #+ I need to put
        box = ax.get_position()
        ax.set_position([box.x0, box.y0 + box.height * vspace,
        box.width, box.height * (1 - vspace)])

x = np.arange(10)
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
n = 3
line = {}
for i in range(3):
    line['lines'].append(ax1.plot(x, i*x**2))
    line['labels'].append(r'$y = %i \cdot x^2$'%i)
ax1.set_title('example plot')

ax2 = ax1.twinx()
line['lines'].append(ax2.plot(x, x^-1, label = r'$y = x^-1$'))
line['labels'].append(r'$y = x^-1$')
leg = ax1.legend(line['lines'], line['labels'])
fig_layout(fig)
#  I will put the legend box at the bottom of the axes with another function.
plt.show()
like image 826
user1850133 Avatar asked May 24 '14 18:05

user1850133


1 Answers

I think you can use fig.get_axes().

For example, to modify the title of the first sub-plot, you can do:

plt.gcf().get_axes()[0].set_title("example plot")
like image 105
Jan Kuiken Avatar answered Oct 06 '22 23:10

Jan Kuiken