I'm plotting a series of data points with x and y error but do NOT want the errorbars to be included in the legend (only the marker). Is there a way to do so?
Example:
import matplotlib.pyplot as plt import numpy as np subs=['one','two','three'] x=[1,2,3] y=[1,2,3] yerr=[2,3,1] xerr=[0.5,1,1] fig,(ax1)=plt.subplots(1,1) for i in np.arange(len(x)): ax1.errorbar(x[i],y[i],yerr=yerr[i],xerr=xerr[i],label=subs[i],ecolor='black',marker='o',ls='') ax1.legend(loc='upper left', numpoints=1) fig.savefig('test.pdf', bbox_inches=0)
You can remove error bars by passing ci=None argument.
If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.
To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.
In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.
You can modify the legend handler. See the legend guide of matplotlib. Adapting your example, this could read:
import matplotlib.pyplot as plt import numpy as np subs=['one','two','three'] x=[1,2,3] y=[1,2,3] yerr=[2,3,1] xerr=[0.5,1,1] fig,(ax1)=plt.subplots(1,1) for i in np.arange(len(x)): ax1.errorbar(x[i],y[i],yerr=yerr[i],xerr=xerr[i],label=subs[i],ecolor='black',marker='o',ls='') # get handles handles, labels = ax1.get_legend_handles_labels() # remove the errorbars handles = [h[0] for h in handles] # use them in the legend ax1.legend(handles, labels, loc='upper left',numpoints=1) plt.show()
This produces
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With