我已经使用 Python 生成了很多数字,并将它们保存在列表中,现在我想将它们绘制在散点图和条形图中,以查看我创建的函数的模式。
我最多得到从 0 到 99,999,999 的数字,我尝试绘制但失败了。
在条形图中,y轴应显示数字在生成的数字范围内重复自身的次数,x轴应显示数字本身。
我尝试使用方法
collections.counter
,但它不断返回给我一个字典,其中包含列表中至少出现一次的所有数字,而不是刚刚重复的数字,以及重复的数字的数据,我想我可以正确绘制图表。
显示我从函数获得的数据的图像
您想在散点图中绘制什么? Matplotlib 有内置的 直方图绘图仪。
import random
import matplotlib.pyplot as plt
random.seed(0)
ITER = 20
LOW = 0
HIGH = 10
RND_NUMS = []
for _ in range(ITER):
RND_NUMS.append(random.randint(LOW, HIGH))
plt.hist(RND_NUMS, bins=range(0,10))
这会产生类似的结果:
您可以使用 NumPy unique 并将返回计数设置为 true,这是一个包含 10 个随机数的示例,
import numpy as np
import matplotlib.pyplot as plt
# random integer array
rand_array=np.random.randint(10, size=10)
u, c=np.unique(rand_array, return_counts=True)
# plot
fig, axs=plt.subplots(1, 2)
axs[0].bar(range(len(c)), c)
axs[0].set_xticks(range(len(c)),u)
axs[0].set_yticks(range(max(c)))
axs[0].set_title('unique counts')
# selecting out the repeated ones
axs[1].bar(range(np.sum(c>1)), c[c>1])
axs[1].set_xticks(range(np.sum(c>1)),u[c>1])
axs[1].set_title('repeated ones')
axs[1].set_yticks(range(max(c)))
plt.show()