python data_error ai_generated true

UserWarning: Data has no positive values, and therefore cannot be log-scaled.

ID: python/matplotlib-log-scale-nonpositive

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-11-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Setting a log scale on an axis whose data contains only zero or negative values.

generic

中文

在仅包含零或负值的数据轴上设置对数缩放。

Workarounds

  1. 90% success
    ax.set_yscale('symlog', linthresh=1)
  2. 88% success
    import numpy as np
    mask = data > 0
    ax.plot(x[mask], data[mask])
    ax.set_yscale('log')

Dead Ends

Common approaches that don't work:

  1. 55% fail

    Clipping silently replaces values with the smallest positive number, producing misleading plots.

  2. 50% fail

    Shifts the entire distribution and can hide genuinely zero categories.