Katt
Katt

Reputation: 1017

ylabel using function subplots in matplotlib

I recently found the function subplots, which seems to be a more elegant way of setting up multiple subplots than subplot. However, I don't seem to be able to be able to change the properties of the axes for each subplot.

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as npx = np.linspace(0, 20, 100)

fig, axes = plt.subplots(nrows=2)

for i in range(10):
    axes[0].plot(x, i * (x - 10)**2)
    plt.ylabel('plot 1')

for i in range(10):
    axes[1].plot(x, i * np.cos(x))
    plt.ylabel('plot 2')

plt.show()

Only the ylabel for the last plot is shown. The same happens for xlabel, xlim and ylim.

I realise that the point of using subplots is to create common layouts of subplots, but if sharex and sharey are set to false, then shouldn't I be able to change some parameters?

One solution would be to use the subplot function instead, but do I need to do this?

Upvotes: 2

Views: 4847

Answers (1)

Yann
Yann

Reputation: 35463

Yes you probably want to use the individual subplot instances.

As you've found, plt.ylabel sets the ylabel of the last active plot. To change the parameters of an individual Axes, i.e. subplot, you can use any one of the available methods. To change the ylabel, you can use axes[0].set_ylabel('plot 1').

pyplot, or plt as you've defined it, is a helper module for quickly accessing Axes and Figure methods without needing to store these objects in variables. As the documentation states:

[Pyplot p]rovides a MATLAB-like plotting framework.

You can still use this interface, but you will need to adjust which Axes is the currently active Axes. To do this, pyplot has an axes(h) method, where h is an instance of an Axes. So in you're example, you would call plt.axes(axes[0]) to set the first subplot active, then plt.axes(axes[1]) to set the other.

Upvotes: 2

Related Questions