How do I assign multiple labels at once in matplotlib?

前端 未结 9 1489
半阙折子戏
半阙折子戏 2020-12-02 16:41

I have the following dataset:

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

Now I plot it with:

9条回答
  •  抹茶落季
    2020-12-02 17:03

    You can iterate over your line objects list, so labels are individually assigned. An example with the built-in python iter function:

    lineObjects = plt.plot(x, y)
    plt.legend(iter(lineObjects), ('foo', 'bar', 'baz'))`
    

    Edit: after updating to matplotlib 1.1.1, it looks like the plt.plot(x, y), with y as a list of lists (as provided by the author of the question), doesn't work anymore. The one step plotting without iteration over the y arrays is still possible thought after passing y as numpy.array (assuming (numpy)[http://numpy.scipy.org/] as been previously imported).

    In this case, use plt.plot(x, y) (if the data in the 2D y array are arranged as columns [axis 1]) or plt.plot(x, y.transpose()) (if the data in the 2D y array are arranged as rows [axis 0])

    Edit 2: as pointed by @pelson (see commentary below), the iter function is unnecessary and a simple plt.legend(lineObjects, ('foo', 'bar', 'baz')) works perfectly

提交回复
热议问题