英文:
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 < 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 < 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()
答案1
得分: 1
问题出在以下代码行:
return z0 if z0 < 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 >= 0] = np.log(1 + z0[z0 >= 0])
return z0
切片操作允许您仅更改数组中您想要的元素。
英文:
The problem is in the line of code:
return z0 if z0 < 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 >= 0] = np.log(1 + z0[z0 >= 0])
return z0
The slicers allow you to change just the elements you want from an array.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论