仅显示图例 Python Matplotlib 中的某些项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24680981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:00:31  来源:igfitidea点击:

Show only certain items in legend Python Matplotlib

pythonmatplotliblegend

提问by Funsaized

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:

我目前正在绘制大量分类数据的堆积条形图,并且只希望显示图例中的重要物种(我希望显示约 500 个物种中的约 25 个)。有没有一种简单的方法可以做到这一点?下面是我的代码:

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

采纳答案by Trond Kristiansen

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

这将创建以下图: 在此处输入图片说明

回答by jlansey

This works:

这有效:

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

source

来源

回答by Andrey Selivanov

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

传奇还需要艺术家列表和标签列表,以精确控制进入您的传奇的内容 – tacaswell 2014 年 7 月 11 日 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:

代码的结果: 代码的结果:

回答by Enrique Millán Valbuena

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.

通过传递一个空的 str() 对象,它不会写下任何东西。

Matplotlib API reference

Matplotlib API 参考