如何在matplotlib中标记总额的部分?

How to mark parts of the total amount in matplotlib?

我正在尝试使用 pythons matplotlib 创建一个简单的直方图。

关于评论长度的分布。我有几千条评论,我已经有了下面的代码:

x = [60, 55, 2, 30, ..., 190]

plt.hist(x, bins=100)
plt.xlim(0,150)
plt.grid(axis="x")
plt.title("Distribution of Comment Lengths")
plt.xlabel("Tokens/Comment")
plt.ylabel("Amount of Comments")
plt.show()

我想实现的是一种显示我已经通过所有令牌的 50%(或 33% 和 66%,或 25%、50% 和 75%)的方法。我在想象一条垂直线将分布分成两半,两边的代币数量相等。

matplotlib 是否提供了轻松实现这一目标的机会?

感谢您的帮助!

要获取所有评论的p%对应的x值,只需对值列表进行排序,然后将其索引到总长度的p%处。您可以在这些位置添加垂直线,并添加第二个 x 轴来标记它们。

要得到所有token的p%对应的x值,找到值为p% of the sum of all the x's的元素在排序列表的累加和数组中的位置。使用该位置索引排序的值列表。

这里有一些代码来展示它是如何工作的。

from matplotlib import pyplot as plt
import numpy as np

# create some random data to test, convert to a regular Python list to be similar to the question
x = list(np.abs(np.random.normal(85, 30, 2000)))
wanted_percentiles = [5, 10, 25, 33, 50, 66, 75, 90, 95]
sx = np.array(x)
sx.sort()
cx = sx.cumsum()

percentile_sx = [sx[int(len(x) * p / 100)] for p in wanted_percentiles]
percentile_cx = [sx[cx.searchsorted(cx[-1] * p / 100)] for p in wanted_percentiles]

fig, axes = plt.subplots(ncols=2, figsize=(12, 4))
for ax, percentile, color, title in zip(axes, [percentile_sx, percentile_cx],
                                 ['crimson', 'limegreen'], ['Comments Percentile', 'Tokens Percentile']):
    ax.hist(x, bins=20)
    for xp in percentile:
        ax.axvline(xp, color=color)
    ax2 = ax.twiny()

    ax.set_xlim(0, 150)
    ax2.set_xlim(ax.get_xlim())  # both axes need exactly the same limits
    ax2.set_xticks(percentile)  # use the xs corresponding to the percentiles as tick positions
    ax2.set_xticklabels(wanted_percentiles, color=color) # use the percentiles to label the ticks
    ax.set_title("Distr. of Comment Lengths, " + title)
    ax.set_xlabel("Comments binned via number of tokens")
    ax.set_ylabel("Amount of Comments")
plt.show()

左边是有 100 个 bin 的图,右边是有 20 个 bin 的图: