首页 > 解决方案 > 出现次数的 Matplotlib 条形图

问题描述

我想为列表的出现次数制作一个条形图。更具体地说,我从如下列表开始:

>>> print(some_list)
[2, 3, 10, 5, 20, 34, 50, 10, 10 ... ]

这个列表基本上是 [0, 2470] 范围内的整数。我想要做的是绘制每个整数的出现次数。我写的代码是:

from collections import Counter

import matplotlib.pyplot as plt
import pandas as pd


sorted_list = sorted(some_list)
sorted_counted = Counter(sorted_list)

range_length = list(range(max(some_list))) # Get the largest value to get the range.
data_series = {}

for i in range_length:
    data_series[i] = 0 # Initialize series so that we have a template and we just have to fill in the values.

for key, value in sorted_counted.items():
    data_series[key] = value

data_series = pd.Series(data_series)
x_values = data_series.shape[0]

plt.bar(x_values, data_series.values)
plt.show()

当我运行此代码时,我得到以下图:

在此处输入图像描述

这不是我要找的。

我期望的图中 $x$ 值是 [0, 2740] 中的值,$y$ 值应该是每个整数值的出现次数。它应该看起来像一个反向指数图。

我的代码有什么问题?提前致谢。

标签: pythonmatplotlib

解决方案


该行x_values = data_series.shape[0]引起了问题:这会将您的 x_values 变成 data_series 的第一个维度(单个值),这不是您想要的。改用x_values = data_series.index它会给你一个列表,列出所有整数,直到出现的最高整数。

为了证明它是可推广的,这就是我使用泊松分布得到的结果。

from collections import Counter

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

some_list = np.random.poisson(500, 2470).tolist()

sorted_list = sorted(some_list)
sorted_counted = Counter(sorted_list)

range_length = list(range(max(some_list))) # Get the largest value to get the range.
data_series = {}

for i in range_length:
    data_series[i] = 0 # Initialize series so that we have a template and we just have to fill in the values.

for key, value in sorted_counted.items():
    data_series[key] = value

data_series = pd.Series(data_series)
x_values = data_series.index

# you can customize the limits of the x-axis
# plt.xlim(0, max(some_list))
plt.bar(x_values, data_series.values)

plt.show() 

在此处输入图像描述


推荐阅读