python - 出现次数的 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$ 值应该是每个整数值的出现次数。它应该看起来像一个反向指数图。
我的代码有什么问题?提前致谢。
解决方案
该行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()
推荐阅读
- reactjs - 在 React Hooks 中如何更好地使用 Redux useSelector
- angular8 - 如何在 dist/ 生成的 index.html 中注入脚本以索引 html 文件
? - android - Integrate Android Studio Project with Azure Pipelines CI/CD
- c# - 如何在 teechart 的任何事件上获取自定义轴
- c# - change mouse button function
- apache - Jmeter 和 Jenkins 集成以生成 Perfmon 图
- c# - 如何在 Blazor 的 DevExpress 数据网格中加载 null 或空集合?
- r - 在 R Markdown 中将一个长方程分成两行
- regex - PL/SQL 正则表达式匹配逗号不在引号内
- c# - 在 1 中组合 2 个或多个正则表达式