【问题标题】:matplotlib legend title on single row with legend labels带有图例标签的单行上的 matplotlib 图例标题
【发布时间】:2019-05-28 20:36:21
【问题描述】:

我正在使用图例标题(通过 matplotlib),它将标题放在图例条目上方,但是我想在情节下创建一个细长的图例。 ncol 将创建单行图例条目,但我不知道如何在同一行获取图例标题。

MWE

import numpy as np

%matplotlib notebook
import matplotlib
from matplotlib import pyplot as plt

X1 = np.random.rand(50)
X2 = np.random.rand(50)
Y = np.random.rand(50)

plt.plot(X1,Y,X2,Y)
plt.legend(labels = ['X1','X2'],ncol=2,title='legend title:',loc=3)

我希望图例看起来像

图例标题:----- X1 ----- X2

而不是

图例标题:
----- X1 ----- X2

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这是一个代码 -

    labels =["X1", "X2"]
    fig, ax = plt.subplots()
    val = [X1, X2]
    for i in range(2):
        ax.plot(val[i], Y, label=labels[i]) # Plotting one at a time
    h, l = ax.get_legend_handles_labels() # Extracting handles and labels
    ph = [plt.plot([],marker="", ls="")[0]] # Canvas
    handles = ph + h
    labels = ["legend title:"] + l  # Merging labels
    plt.legend(handles, labels, ncol=3)
    plt.show()
    

    更多信息,请参考here

    【讨论】:

      猜你喜欢
      • 2014-11-26
      • 2023-04-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      相关资源
      最近更新 更多