使用 Matplotlib 的散点图
时,自动缩放有时有效,有时无效。
如何修复它?
如错误报告中提供的示例所示,此代码有效:
plt.figure()
x = np.array([0,1,2,3])
x = np.array([2,4,5,9])
plt.scatter(x,y)
但是当使用较小的值时,缩放将无法工作:
plt.figure()
x = np.array([0,1,2,3])
x = np.array([2,4,5,9])
plt.scatter(x/10000,y/10000)
编辑:可以找到一个示例 here 。我没有在问题中指定具体原因,因为遇到错误时并不明显是什么原因导致的。另外,我已经在自己的答案中指定了解决方案和原因。
最佳答案
至少在 Matplotlib 1.5.1 中,存在一个错误,即小数据值的自动缩放失败,如报告 here .
解决方法是使用 .set_ylim(bottom,top)
( documentation ) 手动设置数据限制(在此示例中,对于 y 轴,要设置 x 轴,请使用 .set_xlim(左,右)
.
要自动找到令人满意的数据限制,可以使用以下伪代码:
def set_axlims(series, marginfactor):
"""
Fix for a scaling issue with matplotlibs scatterplot and small values.
Takes in a pandas series, and a marginfactor (float).
A marginfactor of 0.2 would for example set a 20% border distance on both sides.
Output:[bottom,top]
To be used with .set_ylim(bottom,top)
"""
minv = series.min()
maxv = series.max()
datarange = maxv-minv
border = abs(datarange*marginfactor)
maxlim = maxv+border
minlim = minv-border
return minlim,maxlim
关于python - Matplotlib 散点图轴自动缩放对于小数据值失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37634370/