Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only certain items in legend Python Matplotlib

I currently am plotting a stacked bar graph of a large amount of taxonomic data, and only wish to show significant species in the legend (out of ~500 I wish to show ~25). Is there a simple way to do this? Below is the code I have:

labels=['0','20','40','60','80','100','120']
ax1=subj1df.plot(kind='barh', stacked=True,legend=True,cmap='Paired', grid=False)
legend(ncol=2,loc=2, bbox_to_anchor=(1.05, 1), borderaxespad=0.)
label1=['Baseline','8h','24h','48h','96h','120h']
ax1.set_yticklabels(label1, fontdict=None, minor=False)
plt.title('Subject 1 Phyla',fontweight='bold')
plt.savefig('Subject1Phyla.eps', format='eps', dpi=1000)
ax1.set_xticklabels(labels)

Edit: tried adding this to show only one legend entry, however only returns an empty legend:

h, l = ax1.get_legend_handles_labels()
legend(l[4],h[4],ncol=2,loc=2, bbox_to_anchor=(1.05, 1), borderaxespad=0.)
like image 780
Funsaized Avatar asked Jul 10 '14 15:07

Funsaized


People also ask

How do you skip a legend entry in Python?

@sid100158- To exclude one or more elements from the legend, pass no label or label='nolegend'. for your question you can use this command to exclude one or more elements from the legend. Hope this helps!

Is PLT show () blocking?

Answer #1: show() (not with block=False ) and, most importantly, plt. pause(. 001) (or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing.

How do I specify the position of legend in matplotlib?

A legend is an area describing the elements of the graph. In the matplotlib library, there's a function called legend() which is used to Place a legend on the axes. The attribute Loc in legend() is used to specify the location of the legend. Default value of loc is loc=”best” (upper left).


4 Answers

This works:

plt.plot(x, y, label='_nolegend_') 

source

like image 54
jlansey Avatar answered Sep 28 '22 19:09

jlansey


I often insert an empty label for legends I don't want to show. I made an extremely simple example which I hope will help you. You will need to tweak this to your own data but the elements you need should be there.

import matplotlib.pyplot as plt  import numpy as np  myY=np.random.randint(20, size=10) myX=np.arange(0,len(myY))  selected=[5,10,15]  fig = plt.figure() for X,Y in zip(myX,myY):     if Y in selected:         mylabel="label = %s"%(Y); mycolor='blue'     else:         mylabel=None; mycolor='red'     plt.scatter(X,Y,50, color=mycolor, label=mylabel) plt.legend() plt.show() 

This creates the following plot: enter image description here

like image 35
Trond Kristiansen Avatar answered Sep 28 '22 21:09

Trond Kristiansen


For whatever reason both answers didn't work for mine situation. What worked, and actually was indicated above:

legend also takes a list of artists and a list of labels to precisely control what goes into your legend – tacaswell Jul 11 '14 at 4:46

import pandas as pd
import matplotlib.pyplot as plt
import pylab

pd.Series(range(10)).plot(color = 'grey')
x = list(range(10))
y = [i + 1 for i in x]  
scat1 = plt.scatter(x, y)

pylab.legend([scat1],['moved points'], loc = 'upper left')

plt.show()

The result of the code: The result of the code:

like image 42
Andrey Selivanov Avatar answered Sep 28 '22 19:09

Andrey Selivanov


You can also use an empty string variable:

    plt.plot(xData, yData, ..., label=str())

By passing an empty str() object, it doesn't write down anything.

Matplotlib API reference

like image 31
Enrique Millán Valbuena Avatar answered Sep 28 '22 19:09

Enrique Millán Valbuena