matplotlib.pyplot绘图可在同一坐标中绘制多个点。如何显示每个坐标上有多少个点?

时间:2020-09-24 15:21:33

标签: python matplotlib

The graph obtained

plt.xlabel('Half Time Result')
plt.ylabel('Full Time Result')
plt.scatter(htr, ftr, marker='.', color='black')
plt.savefig('htrvsftr')

1 个答案:

答案 0 :(得分:2)

您可以添加一些随机抖动,例如,为每个坐标添加一个小的高斯随机值:

import numpy as np
import matplotlib.pyplot as plt

htr = np.random.randint(1, 9, 500)
ftr = np.random.randint(1, 6, 500)

plt.xlabel('Half Time Result')
plt.ylabel('Full Time Result')
plt.scatter(htr + np.random.normal(0, .1, htr.size), ftr + np.random.normal(0, .1, ftr.size),
            marker='.', color='black')
plt.show()

example plot

除了np.random.normal(0, .1)以外,还可以使用均匀分布,例如np.random.uniform(-.4, .4)。如果还有更多的重合点,则可以另外设置一个alpha值。

为了更好地显示差异,可以绘制二维直方图,例如通过seaborn's jointplot

当x和y值为字符串类型时,您可以从散点图中提取偏移位置,添加随机抖动并更新位置:

import numpy as np
import matplotlib.pyplot as plt

htr = np.random.choice(['H', 'D', 'A'], 500)
ftr = np.random.choice(['H', 'D', 'A'], 500)
scatter_dots = plt.scatter(htr, ftr, marker='.', color='black', alpha=0.3)

xy = scatter_dots.get_offsets()
scatter_dots.set_offsets(xy + np.random.normal(0, .1, size=xy.shape))
plt.xlabel('Half Time Result')
plt.ylabel('Full Time Result')
plt.xlim(-0.5, 2.5)
plt.ylim(-0.5, 2.5)
plt.show()

example with categorical axes

jointplot可能是这样的:

import seaborn as sns

sns.jointplot(x=htr, y=ftr, kind="hist",
              joint_kws={'bins': (np.arange(-0.5, 3), np.arange(-0.5, 3))},
              marginal_kws={'lw': 1})

jointplot example

相关问题