Search code examples
pythonmatplotlibaxis-labelssubplot

Matplotlib; making different subplots with different axis labels


I am making a figure that consists of 2 subplots. The subplots show different quantities so I would like the axis labels to be different. However, I have no idea how to do this with the matplotlib library.

Code example:

import numpy as np
import matplotlib.pyplot as plt

frequency = np.linspace(0, 100, 10)
eta = np.ones(10)

Power = np.linspace(0, 10, 10)
T = np.linspace(0, 10, 10)

fig, ax = plt.subplots(2, 1)
ax[0].plot(frequency, eta)
plt.xlabel('frequency')
ax[1].plot(Power, T)


plt.show()

As you can see in the figure, the label appears underneath the second x-axis. enter image description hereI have tried numerous things such as plt.axlabel('frequency', 'Power') or ax[0].xlabel('frequency') or fig[0].xlabel('frequency'), but none of them seem to work.

Does anyone know how to do this? Thanks very much in advance!


Solution

  • You can try this:

    import numpy as np
    import matplotlib.pyplot as plt
    
    frequency = np.linspace(0, 100, 10)
    eta = np.ones(10)
    
    Power = np.linspace(0, 10, 10)
    T = np.linspace(0, 10, 10)
    
    ax1 = plt.subplot(2, 1, 1)
    plt.plot(frequency, eta)
    plt.xlabel('frequency')
    
    ax2 = plt.subplot(2, 1, 2)
    plt.plot(Power, T)
    plt.xlabel('label 2')
    
    plt.subplots_adjust(hspace = 0.5)
    
    plt.show()
    

    plt.subplot(2, 1, 1) means that the subplots in the figure are in the form of 2 rows and 1 column and the 1st subplot is currently being referred. Similarly, plt.subplot(2, 1, 2) means that the second subplot is being referred.

    Without plt.subplots_adjust(hspace = 0.5), the label of the first subplot is hidden by the second subplot.