How do I assign multiple labels at once in matplotlib?

前端 未结 9 1464
半阙折子戏
半阙折子戏 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:17

    I used the following to show labels for a dataframe without using the dataframe plot:

    lines_ = plot(df)
    legend(lines_, df.columns) # df.columns is a list of labels
    
    0 讨论(0)
  • 2020-12-02 17:21

    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()
    

    Edit: @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.

    0 讨论(0)
  • 2020-12-02 17:24

    If you're using a DataFrame, you can also iterate over the columns of the data you want to plot:

    # Plot figure
    fig, ax = plt.subplots(figsize=(5,5))
    # Data
    data = data
    # Plot
    for i in data.columns:
        _ = ax.plot(data[i], label=i)
        _ = ax.legend() 
    plt.show()
    
    0 讨论(0)
提交回复
热议问题