在Z=0的地方用黑线追踪一个3d图形?

2024-04-19 11:32:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个功能性的三维图形,但是我想在这个图形上画一条当z=0时的迹线。你知道吗

我尝试将z>;=0和z<;0时的图形分开,但这并不能清楚地表示,如注释掉的代码所示。我想用不同的颜色描这条线。另一种解决方案是让部分图形z>;=0是一种颜色,而z<;0是另一种颜色,但我也一直得到一个错误。你知道吗

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np


def equation(delta=0.05):
    #for F=0.5

    x = np.arange(0,1,delta)
    y = np.arange(2,6,delta)
    X,Y = np.meshgrid(x,y)

    Z = (X*Y-X-0.5*Y**2+2*0.5*Y)**2-4*(0.5*Y**2-0.5*Y)*(X-X*Y+Y-0.5*Y)


    return X, Y, Z

#x = P
#y = K

fig = plt.figure()
ax = Axes3D(fig)

#set labels for graph
ax.set_xlabel('P')
ax.set_ylabel('K')
ax.set_zlabel('Z')

#set colors about and below 0
#c = (Z<=0)
#ax.plot_surface(x,y,z,c=c,cmap='coolwarm')

#ax.plot_surface(x,y,z,c= z<0)
c = z=0

x,y,z = equation(0.01)
surf=ax.plot_surface(x,y,z)
#surf=ax.plot_surface(x,y,z<0)
#surf=ax.plot_surface(x,y,z>=0)

#surf =ax.plot_surface(x,y,z, rstride=5, cstride=5)
#surf = ax.plot_trisurf(x,y,z,cmap=cm.jet,linewidth=0.1,vmin=-15, vmax=100)



#surf = ax.plot_surface(x,y,z,rstride = 5, cstride #=5,cmap=cm.RdBu,linewidth=0, antialiased=False)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))




#fig.colorbar(surf, shrink= 0.5, aspect=5)
#ax.view_init(elev=25,azim=-120)
plt.show()

Tags: fromimport图形plotmatplotlib颜色npfig
1条回答
网友
1楼 · 发布于 2024-04-19 11:32:41

当仅仅高亮显示Z=0线时,您需要记住,在该点上,您不再具有曲面,而是二维平面。然后你想找到2D平面等于零的地方。您想使用Poolka建议的ax.contour(x,y,z,[0])。我建议更改绘图中的透明度(alpha),以使该行更可见。你知道吗

您还可以通过创建一个自定义颜色映射并使vminvmax以零为中心,使这两个区域以零2种不同的颜色分开。你知道吗

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib.colors



def equation(delta=0.05):
    x = np.arange(0,1,delta)
    y = np.arange(2,6,delta)
    X,Y = np.meshgrid(x,y)

    Z = (X*Y-X-0.5*Y**2+2*0.5*Y)**2-4*(0.5*Y**2-0.5*Y)*(X-X*Y+Y-0.5*Y)

    return X, Y, Z


fig = plt.figure()
ax = Axes3D(fig)

#set labels for graph
ax.set_xlabel('P')
ax.set_ylabel('K')
ax.set_zlabel('Z')



#Create custom colormap with only 2 colors
colors = ["blue","red"]
cm1 = LinearSegmentedColormap.from_list('my_list', colors, N=2)



x,y,z = equation(0.01)
surf=ax.plot_surface(x,y,z,alpha=.7,cmap=cm1,vmin=-150,vmax=150) #use custom colormap

#Use a contour plot to isolate Z=0 since it is a line and no longer a surface
ax.contour(x,y,z,[0],colors='k',linewidths=3)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))


plt.show()

enter image description here

相关问题 更多 >