python - Matplotlib 散点图轴自动缩放对于小数据值失败

标签 python matplotlib

使用 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/

相关文章:

python - 我们如何使Python脚本在系统启动时(最好是linux)在安装它的每个系统上自动执行?

java - 在 Python 中使用 Unicode 保持 Java 字符串偏移量一致

python - 自定义样式 Pandas 数据框

python - 如何在 Altair 的 HConcatChart 中配置图表位置

python - 重命名子图中的图例 : matplotlib

python - Matplotlib - 将标签移动到饼图的中间

python - 在 Ipython Notebook 中绘制

python - Plotly 未显示所有数据

python - Matplotlib:在极轴上绘制任意向量

python - 通过添加列组来创建新列