python - 如何为条形图选择一系列 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()
解决方案
您已经拥有排序数组中的值,但您只想选择计数最多的十个值。
似乎您的数组以较大的计数作为最后一个值进行排序,因此您可以利用 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')
它按递增顺序绘制。
推荐阅读
- php - 如何在一个页面上使用一个表单两次或三次?
- image - 使用 Selenium 下载全尺寸图像
- testing - TestCafe 可以支持的最大并发是多少
- php - 安装 Composer,在设置检查期间出现错误“PHP 警告:PHP 启动:无法加载动态库 'php_wincache.dll'”
- sql - 按月优化 postgres 查询平均值 [已编辑]
- r - 显式语句有效,但以语句为模型的函数返回空列表
- ios - Obj-C - 将tableview行设置为在加载时选择?
- c++ - 这里的 const 变量有什么意义吗?
- javascript - 如何在重定向时销毁离子组件
- html - 如何在 CSS 中倾斜悬停