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

2024-05-23 20:37:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在绘制一个包含大量分类数据的堆积条形图,并且只希望显示传说中的重要物种(在~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)

编辑:尝试添加此项以仅显示一个图例项,但仅返回空图例:

h, l = ax1.get_legend_handles_labels()
legend(l[4],h[4],ncol=2,loc=2, bbox_to_anchor=(1.05, 1), borderaxespad=0.)

Tags: tofalsetruelabels物种pltlocanchor
3条回答

我经常为不想显示的图例插入空标签。我做了一个非常简单的例子,希望能对你有所帮助。你将需要调整到你自己的数据,但你需要的元素应该在那里。

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

这将创建以下绘图: enter image description here

不管出于什么原因,这两个答案都不适合我的情况。什么有效,实际上是上面指出的:

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:

这是有效的:

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

source

相关问题 更多 >