防止坐标轴切断 matplotlib 散点图中的点

Prevent axes from cutting off dots in matplotlib scatter plots

import matplotlib.pyplot as plt


x = [1, 2, 3, 4]
y = [0, 1, 7, 2]

plt.scatter(x, y, color='red')
plt.title('number of iterations')
plt.xlim([1, 4])
plt.ylim([1, 8])

如果要绘制此数据,轴上的点会被部分切掉。有没有办法防止这种情况(即可以将点绘制在轴的顶部)?

clip_on设置为False:

plt.scatter(x, y, color='red', clip_on=False)

clip_on 属性设置为 False 允许您超越轴,但默认情况下轴将在顶部。例如,脚本

x = [1, 2, 3, 4]
y = [0, 1, 7, 2]

plt.scatter(x, y, color="red", clip_on=False)
plt.title('number of iterations')
plt.xlim([1, 4])
plt.ylim([1, 8])

产生以下结果。

请注意,坐标轴“切穿”了这些点。如果您希望点位于 axes/labels 之上,则需要更改默认值 zorder。例如,脚本

x = [1, 2, 3, 4]
y = [0, 1, 7, 2]

plt.scatter(x, y, color="red", clip_on=False, zorder = 10)
plt.title('number of iterations')
plt.xlim([1, 4])
plt.ylim([1, 8])

产量

注意:任何 zorder 值 3 或更大的值都适用于此处