如何在matplotlib中一次分配多个标签? [英] How do I assign multiple labels at once in matplotlib?

查看:677
本文介绍了如何在matplotlib中一次分配多个标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据集:

x = [0, 1, 2, 3, 4]
y = [ [0, 1, 2, 3, 4],
      [5, 6, 7, 8, 9],
      [9, 8, 7, 6, 5] ]

现在,我将其绘制为:

import matplotlib.pyplot as plt
plt.plot(x, y)

但是,我想用此命令标记3个y数据集,当调用.legend()时会引发错误:

However, I want to label the 3 y-datasets with this command, which raises an error when .legend() is called:

lineObjects = plt.plot(x, y, label=['foo', 'bar', 'baz'])
plt.legend()

File "./plot_nmos.py", line 33, in <module>
  plt.legend()
...
AttributeError: 'list' object has no attribute 'startswith'

当我检查lineObjects时:

>>> lineObjects[0].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[1].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[2].get_label()
['foo', 'bar', 'baz']

问题

是否有一种仅使用.plot()方法分配多个标签的优雅方法?

Question

Is there an elegant way to assign multiple labels by just using the .plot() method?

推荐答案

不可能直接(至少在版本1.1.1中)直接绘制这两个数组,因此您必须遍历y数组.我的建议是同时遍历标签:

It is not possible to plot those two arrays agains each other directly (with at least version 1.1.1), therefore you must be looping over your y arrays. My advice would be to loop over the labels at the same time:

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [ [0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [9, 8, 7, 6, 5] ]
labels = ['foo', 'bar', 'baz']

for y_arr, label in zip(y, labels):
    plt.plot(x, y_arr, label=label)

plt.legend()
plt.show()

@gcalmettes指出,作为numpy数组,可以同时绘制所有线(通过转置它们).参见@gcalmettes答案&有关详细信息的评论.

@gcalmettes pointed out that as numpy arrays, it is possible to plot all the lines at the same time (by transposing them). See @gcalmettes answer & comments for details.

这篇关于如何在matplotlib中一次分配多个标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆