python - 同时添加所有图例标签以进行绘图 (Python)

标签 python matplotlib plot figure

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

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

matplotlibseaborn 中是否有某种类型的方法,您可以在其中为其提供要绘制的数据点数组(在本例中为 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()

enter image description here

最佳答案

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

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

但这意味着您需要将绘图放入变量中。

 plot, = ...

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

关于python - 同时添加所有图例标签以进行绘图 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36162799/

相关文章:

Python 线排序 -

python - 如何在python3中将一个简单的整数矩阵作为输入

python - asfreq() 返回一个空数据框

wolfram-mathematica - matlab 喜欢 Mathematica 中的多线图

python - Matplotlib:Draggable 不适用于使用 twinx() 生成的多个图例

python - 无法比较原始偏移和偏移感知日期时间 - last_seen 选项

Python-从当前文件夹读取文件

python - 将 x 轴刻度标签向左移动一位

python - 无法手动关闭 matplotlib 绘图窗口

python - Bokeh 图 : output file is appending instead of overwritting