python-3.x - 如何用两条不同颜色的线绘制xlabel?

标签 python-3.x matplotlib axis-labels

我有两个不同单位的不同参数(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()

enter image description here

方式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

关于python-3.x - 如何用两条不同颜色的线绘制xlabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56146693/

相关文章:

Python逆向工程师列表理解

python-3.x - 列名和最大值索引

r - 使用 aes_string 时如何包装 X 轴标签?

python-3.x - Azure 中连续运行的作业

python - Pandas - 每个点具有不同颜色图例的散点图

Python:根据日期用不同颜色绘制分散数据

python - 使用 matplotlib 绘制传入的数字流

ggplot2 - 使用第二个变量标记 ggplot2 构面中的轴刻度

python - matplotlib中轴标签文本顶部的位置是什么?

python - 如何避免 Tkinter 中未处理的异常?