如何使用pyplot.imshow为分段函数绘制轮廓

huangapple go评论74阅读模式
英文:

How can I draw a contour for a piecewise function with pyplot.imshow

问题

以下是您的代码的翻译部分:

import numpy as np
import matplotlib.pyplot as plt

def z(x, y):
    z0 = (x - 1) ** 10 + 5 * (x - 1) ** 5 * (y - 1) ** 5 + (y - 1) ** 10
    # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    return z0 if z0 < 0 else np.log(1 + z0)

def main():
    x, y = np.linspace(0.0, 3.0, 300), np.linspace(0.0, 3.0, 300)
    X, Y = np.meshgrid(x, y)
    plt.imshow(z(X, Y), origin='lower', extent=[0, 3, 0, 3], cmap=plt.cm.hsv)
    plt.colorbar()
    plt.show()

if __name__ == '__main__':
    main()

希望这可以帮助您解决问题。如果您有任何其他问题,请随时提问。

英文:

My function is z = (x - 1) **10 + 5*(x - 1)**5*(y - 1)**5 + (y - 1)**10. However, the contour can't show clear about negative value because of large positive value.

So I just need to show positive value by logarithm (np.log(1 + 0) if z &lt; 0), but keep negative as origin.

How can I do this with pyplot.imshow?

This code doesn't work:

import numpy as np
import matplotlib.pyplot as plt

def z(x, y):
    z0 = (x - 1) **10 + 5*(x - 1)**5*(y - 1)**5 + (y - 1)**10
    # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    return z0 if z0 &lt; 0 else np.log(1 + z0)

def main():
    x, y = np.linspace(0.0, 3.0, 300), np.linspace(0.0, 3.0, 300)
    X, Y = np.meshgrid(x, y)
    plt.imshow(z(X, Y), origin=&#39;lower&#39;, extent = [0, 3, 0, 3], cmap=plt.cm.hsv)
    plt.colorbar()
    plt.show()

if __name__ == &#39;__main__&#39;:
    main()

答案1

得分: 1

问题出在以下代码行:

return z0 if z0 &lt; 0 else np.log(1 + z0)

这行代码引发了一个 ValueError,因为您正在比较一个数组与一个标量。在使用 NumPy 数组时,我建议使用切片操作:

def z(x, y):
    z0 = (x - 1) ** 10 + 5 * (x - 1) ** 5 * (y - 1) ** 5 + (y - 1) ** 10
    z0[z0 &gt;= 0] = np.log(1 + z0[z0 &gt;= 0])
    return z0

切片操作允许您仅更改数组中您想要的元素。

英文:

The problem is in the line of code:

return z0 if z0 &lt; 0 else np.log(1 + z0)

This line raises a ValueError because you are comparing an array with a scalar. When using NumPy arrays, I would suggest using slicers:

def z(x, y):
    z0 = (x - 1) **10 + 5*(x - 1)**5*(y - 1)**5 + (y - 1)**10
    z0[z0 &gt;= 0] = np.log(1 + z0[z0 &gt;= 0])
    return z0

The slicers allow you to change just the elements you want from an array.

huangapple
  • 本文由 发表于 2023年7月17日 14:25:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定