【问题标题】:How to plot the xlabel in two lines of different colors?如何用两条不同颜色的线绘制 xlabel?
【发布时间】:2019-10-02 10:35:42
【问题描述】:

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

【问题讨论】:

    标签: python-3.x matplotlib axis-labels


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢!你太好了!我已经考虑了这两种选择,多亏了你,我现在可以选择我最喜欢的了。
    猜你喜欢
    • 2015-03-18
    • 2013-02-07
    • 2013-06-18
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    相关资源
    最近更新 更多