Search code examples
python-2.7matplotliblegenderrorbarjupyter-lab

Matplotlib legend colors differ from plot colors - bug or error?


I plot data with error bars and want to label them in the legend. However, the colors in the legend don't match the colors in the plot.

toy example:

import matplotlib.pyplot as plt
plt.figure()
plt.plot(np.arange(50),label='data')
plt.errorbar(np.arange(50),np.arange(50),yerr=np.arange(50),label='errors')
plt.legend()

resulting plot

Is this behavior a bug or am I doing something wrong?

Thanks!

I am using python 2.7 and jupyter lab


Solution

  • You have a line for the plot as well as one for the errorbar. One hides the other.

    You may set the linestyle of the errorbar to "None".

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.figure()
    plt.plot(np.arange(50),label='data')
    plt.errorbar(np.arange(50),np.arange(50),yerr=np.arange(50),ls="None",
                 label='errors')
    plt.legend()
    
    plt.show()
    

    enter image description here

    You may also set the zorder of the plot to a higher number to let it appear in front.

    enter image description here