生成随机分布时强制转换为int

2024-05-17 11:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在乱画随机分布图时发现,当我画int创建的分布图时,会出现模糊但清晰且间隔规则的线条(随机。随机() * 随机。随机()). 以下是我使用的代码:

import random
import matplotlib.pyplot as plt

x = []
y = []

for i in range(50000):
    x.append(int(100*(random.random() + random.random())))
    y.append(int(100*(random.random() + random.random())))

plt.figure(figsize = (12,12))
plt.scatter(x,y,s=3)

这是我得到的图表:

Scatter-plot of distribution with distinct faint lines

如果取出整数类型,则整个过程看起来与预期一样:

Scatter-plot of distribution without integer casting

奇怪的是,似乎只有x轴负责垂直线,因为移除x轴上的铸件可以去除垂直线。y轴不显示任何微弱的水平线,但有两条较暗的线。你知道吗

Scatter-plot with integer casting removed on the x-axis only

很明显,较暗的线条与转换为整数有关,但为什么以及如何以这种方式影响总体分布。另外,为什么它只是在垂直方向上,而不是在两个维度上对称应用?你知道吗


Tags: 代码import间隔matplotlib规则分布图plt整数
1条回答
网友
1楼 · 发布于 2024-05-17 11:36:00

它很可能是与matplotlib如何决定在绘图过于“拥挤”时从绘图中删除哪些点有关的工件。例如,在我的屏幕上,我得到了一个具有紧密间隔线的绘图-请参见plot with size=(12,12),而将绘图大小减小到(10, 10)会导致this image。你知道吗

另外,将点数减少到10000(在我的例子中=我的屏幕)会导致size=(12,12)Plot with size=(12,12) and 10000 points的无行绘图


作为一个实验,让我们绘制一组均匀分布的点:

import numpy as np
import matplotlib.pyplot as plt
y, x = np.meshgrid(np.arange(100), np.arange(100))
plt.figure(figsize = (5,5))
plt.scatter(x.ravel(), y.ravel(), s=3)
plt.show()

Here is the result for the uniformly spaced points

相关问题 更多 >