如何用两条不同颜色的线绘制 xlabel?

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

我有两个不同的参数(行 y1 和 y2),我想在同一个图中绘制不同的单位,因为它们各自的值具有相似的大小。因此,我想将它们各自的单位(单位 y1 和单位 y2)分别放在一行中的 xlabel 中,并在行的颜色之后为每一行着色。我该怎么做?

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()

一种方法是使用plt.text 来放置标签。虽然不清楚您希望如何放置标签,但我会回答两种可能的方式

方式一

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()

方式二

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()