【问题标题】:How to select a range of NumPy values for bar chart如何为条形图选择一系列 NumPy 值
【发布时间】:2021-04-28 18:54:01
【问题描述】:

我使用 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()

【问题讨论】:

  • obj 是熊猫数据框吗?直接在熊猫方面这样做会更直接
  • 不,都是用numpy的。这只是我从老板那里得到的一大组代码中的一部分,我不想把它拆开,因为我是个菜鸟。如果有任何建议使用 numpy 数组,那将是首选。

标签: python matplotlib bar-chart


【解决方案1】:

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

您的数组似乎以较大的计数作为最后一个值进行排序,因此您可以利用 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')

按递增顺序绘制。

【讨论】:

  • 效果很好,谢谢!感谢您解释开始和结束索引,这更有意义。
  • 很高兴为您提供帮助。 Numpy 的索引功能非常强大。如果这解决了您的问题,请考虑将答案标记为已接受。
【解决方案2】:

帮自己一个忙,了解Numpy Indexing

在这个简单的例子中,数组的最后 10 个元素由符号 [-10:] 表示,您可以从最后一个元素减去 10 到最后一个元素进行读取。

import numpy as np
import matplotlib.pyplot as plt

# syntetic data
np.random.seed(20210428)
SpeciesList2014 = np.random.randint(0, 100, 2000)

# this is from your code
species, counts = np.unique(SpeciesList2014, return_counts=True)
topindices = np.argsort(counts)[-10:]

# here you probably can have, simply, topspecies = species[topindices]
topspecies = [repr(label) for label in species[topindices]]
topcounts  = counts[topindices]

# plotting
plt.bar(topspecies, topcounts)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-14
    • 2021-10-29
    • 2021-01-03
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    相关资源
    最近更新 更多