Search code examples
python-3.xmatplotlibaxis-labels

How to plot the xlabel in two lines of different colors?


I have two different parameters (lines y1 and y2), of different units which I want to plot in the same figure because their individual values are of similar magnitude. I therefore want to put their respective units (Unit y1 and Unit y2) in the xlabel in one row each and color each row after the color of the line. How can I do this?

import numpy as np
import matplotlib as plt

x1 = np.arange(0, 10, 1)
y1 = np.arange(10, 0, -1)
x2 = np.arange(11, 21, 1)
y2 = np.arange(0, 10, 1)

plt.figure()
plt.plot(x1, y1, 'blue')
plt.plot(x2, y2, 'red')
plt.xlabel('Unit y1\n''Unit y2')
plt.show()

Solution

  • One way is to use plt.text to put the labels. While it is unclear how you want the labels to be positioned, I will answer both possible ways

    Way 1

    import matplotlib.pyplot as plt
    
    # Rest of the code
    
    fig, ax = plt.subplots()
    plt.plot(x1, y1, 'blue')
    plt.plot(x2, y2, 'red')
    plt.text(0.2, -0.15, 'Unit y1', color='blue', transform=ax.transAxes)
    plt.text(0.7, -0.15, 'Unit y2', color='red', transform=ax.transAxes)
    plt.show()
    

    enter image description here

    Way 2

    fig, ax = plt.subplots()
    plt.plot(x1, y1, 'blue')
    plt.plot(x2, y2, 'red')
    plt.text(0.45, -0.15, 'Unit y1', color='blue', transform=ax.transAxes)
    plt.text(0.45, -0.2, 'Unit y2', color='red', transform=ax.transAxes)
    plt.show()
    

    enter image description here