在python中为matplotlib图动态添加图例 [英] Dynamically add legends to matplotlib plots in python

查看:56
本文介绍了在python中为matplotlib图动态添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中有一组图,想分别为每个图添加图例.我正在 for 循环中生成图并希望动态添加图例.

I have a set of plots in python and want to add legends to each of them separately. I am generating the plots in a for loop and want to add the legends dynamically.

我只得到显示的最后一个图例.我希望显示所有 9 个

Im getting only the last legend shown. I want all 9 off them to be displayed

for q in range(1,10):
      matplotlib.pylab.plot(s_A_approx, label = q)
matplotlib.pylab.legend(loc = 'upper left')
matplotlib.pylab.show()

推荐答案

我无法重现您的问题.通过对脚本进行一些调整,您可以期待的对我有用.

I can't reproduce your problem. With a few adjustments to your script, what you're expecting is working for me.

import matplotlib.pylab
import numpy as np

for q in range(1,10):
    # create a random, 100 length array
    s_A_approx = np.random.randint(0, 100, 100)
    # note I had to make q a string to avoid an AttributeError when 
    # initializing the legend
    matplotlib.pylab.plot(s_A_approx, marker='.', linestyle='None', label=str(q))

matplotlib.pylab.legend(loc='upper left')
matplotlib.pylab.show()

如果有帮助,这是我的 matplotlib 版本:

If it helps, here's my matplotlib version:

>>> import matplotlib
>>> matplotlib.__version__
'1.0.1'

这篇关于在python中为matplotlib图动态添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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