python runtime_error ai_generated true

ValueError: Number of contour levels must be at least 2, got 1.

ID: python/matplotlib-contour-levels-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-06-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.7 active
3.8 active

Root Cause

Passing a single value for levels parameter in contour/contourf, which requires at least two levels to draw contours.

generic

中文

向contour/contourf的levels参数传递了单个值,但绘制等高线至少需要两个级别。

Workarounds

  1. 95% success Provide at least two levels as an array
    plt.contour(X, Y, Z, levels=[0, 1, 2])
  2. 90% success Use an integer to specify the number of automatically chosen levels
    plt.contour(X, Y, Z, levels=10)  # at least 2

Dead Ends

Common approaches that don't work:

  1. Using a negative number of levels 90% fail

    Levels must be positive integers or an array; negative numbers raise a different error.

  2. Setting levels as a string like 'auto' 70% fail

    In some versions, 'auto' is not a valid input; it must be a number or array.