【问题标题】:Add all legend labels simultaneously to plot (Python)同时将所有图例标签添加到绘图(Python)
【发布时间】:2016-07-09 20:04:43
【问题描述】:

我想同时为plt.plot 对象添加标签。 matplotlib 真的让我很困惑,因为似乎有一百万种方法可以绘制一个数字。有些人做fig, ax = plt.subplots,而其他人只做plt.plot。如果我搜索,我可以找到更多。

无论如何,如何在一行中添加所有标签和数据,而无需循环?我一直在尝试使用seaborn,但我不知道如何让它做简单的折线图,这就是我使用matplotlib 的原因。

matplotlib 或 seaborn 中是否有某种类型的方法,您可以在其中给它一个数据点数组来绘制(在本例中为 80 个点的 3 个样本)以及标签以获得这种类型情节?

在下面给出我的代码,以便您看到我正在从中构建绘图的 DataFrame,但问题最重要的部分是在 #____________________________ 之后

不是How do I assign multiple labels at once in matplotlib? 的副本,因为问题是直接询问如何在没有 for 循环的情况下将其设置在一行中。建议的“重复”类似于下面我的答案的解决方案。

"""Softmax."""

scores = [3.0, 1.0, 0.2]

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    return(np.exp(x) / np.sum(np.exp(x),axis=0))


# Plot softmax curvesy

x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])
DF_activation = pd.DataFrame(softmax(scores).T,index=x,columns=["x","1.0","0.2"])

#____________________________
#I have to add them like this
[plt.plot(DF_activation.index,DF_activation[c], linewidth=3,label=c) for c in DF_activation.columns]
#But I want to add them like this
#plt.plot(DF_activation.index,DF_activation,label=DF_activation.columns,linewidth=2)
plt.xlabel("x")
plt.ylabel("softmax")
plt.legend()

plt.show()

【问题讨论】:

  • 如果你有 mpl 1.5,它更能感知 pandas,并且会提取标签的系列名称,你可以这样做 ax.plot(idx, 'col1', idx, 'col2', data=df)。你为什么关心你是否可以在一行中做到这一点?如果你真的想要这个,只需编写一个带有 forloop 的辅助函数def one_liner_plot(ax, df):。

标签: python matplotlib plot figure


【解决方案1】:

我假设您的意思是图例的标签。您可以在一条指令中直接声明labels 及其引用的对象:

 legend((plot1, plot2, plot3), ('label1', 'label2', 'label3'))

但这意味着你需要将你的情节放入一个变量中。

 plot, = ...

而不仅仅是使用变量来引用图例函数中的标签列表。

【讨论】:

    猜你喜欢
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多