首页 > 解决方案 > 如何为条形图选择一系列 NumPy 值

问题描述

我使用 Matplotlib 根据 NumPy 数组中唯一字符串的计数创建了一个条形图。现在我想在条形图中只显示前 10 个最常见的物种。我是 Python 新手,所以我很难弄清楚。这也是我在这里的第一个问题,所以如果我遗漏任何重要信息,请告诉我

test_indices = numpy.where((obj.year == 2014) & (obj.native == "Native"))
SpeciesList2014 = numpy.append(SpeciesList2014, obj.species_code[test_indices])

labels, counts = numpy.unique(SpeciesList2014, return_counts=True)
indexSort = numpy.argsort(counts)
plt.bar(labels[indexSort][::-1], counts[indexSort][::-1], align='center')
plt.xticks(rotation=45)
plt.show()

标签: pythonmatplotlibbar-chart

解决方案


您已经拥有排序数组中的值,但您只想选择计数最多的十个值。

似乎您的数组以较大的计数作为最后一个值进行排序,因此您可以利用 numpy 索引作为

plt.bar(labels[indexSort][-1:-11:-1], counts[indexSort][-1:-11;-1], align='center')

其中[a:b:c]表示 a=开始索引,b=结束索引 c= 步长,负值表示从数组末尾开始计数。或者:

n=counts.shape[0]
plt.bar(labels[indexSort][n-11:], counts[indexSort][n-11:], align='center')

它按递增顺序绘制。


推荐阅读