如何在图下添加图例?

时间:2019-08-20 16:54:07

标签: python python-3.x jupyter-notebook data-visualization

试图将图例添加到折线图中,但无法执行。请提出一些方法或解决方案。

counts, bin_edges = np.histogram(df_status_1['nodes'], bins=10, 
density = True)
pdf = counts/(sum(counts))
print(pdf);
print(bin_edges);
cdf = np.cumsum(pdf)
plt.plot(bin_edges[1:],pdf);
plt.plot(bin_edges[1:], cdf)

counts, bin_edges = np.histogram(df_status_2['nodes'], bins=10, 
density = True)
pdf = counts/(sum(counts))
print(pdf);
print(bin_edges);
cdf = np.cumsum(pdf)
plt.xlabel('nodes');
plt.ylabel('values');
plt.title('CDF of long & short surviving ppl');
plt.plot(bin_edges[1:],pdf);
plt.plot(bin_edges[1:], cdf)

试图添加plt.legend(),但收到“找不到带有标签的句柄,未插入图例的错误”。请在此处输入代码

1 个答案:

答案 0 :(得分:1)

使用逗号将每个plt.plot存储到轴(plt.plot返回元组)

例如:

arr1, = plt.plot(bin_edges[1:],pdf);
arr2, = plt.plot(bin_edges[1:], cdf)
plt.legend([arr1,arr2], ['PDF survived','CDF survived']) 

尝试如上所述。