我想同时向 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()
最佳答案
我假设您指的是图例的标签。您可以在一条指令中直接声明 labels以及它们引用的对象:
legend((plot1, plot2, plot3), ('label1', 'label2', 'label3'))
但这意味着您需要将绘图放入变量中。
plot, = ...
不仅仅是使用变量来引用图例函数中的标签列表。
关于python - 同时添加所有图例标签以进行绘图 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36162799/