【问题标题】:How to plot a curve for a function in a 3D graphic - Python如何在 3D 图形中为函数绘制曲线 - Python
【发布时间】:2023-04-03 23:58:01
【问题描述】:

我有这个功能:

z = 0.000855995633558468*x**2 + 0.0102702516120239*x + 0.00451027901725375*y**2 - 2.23785431578513*y + 251.029058292935

我也有这个函数的点坐标列表(X,Y,Z)。然后我制作了这段代码来绘制该坐标的图:

fig = plt.figure()
ax = fig.gca(projection='3d')
plt.plot(X, Y, Z)

plt.show() 

如您所见,使用此代码,我按段连接点。如何绘制通过这些点的曲线?

【问题讨论】:

    标签: python plot graph 3d curve


    【解决方案1】:

    简而言之,Python 不知道如何将所有 xyz 点相互连接以创建曲面,因此它只是在它们之间绘制线。

    如果要绘制 z 坐标是其 x 和 y 坐标函数的曲面,则需要创建一个包含所有可能的 xy 坐标组合的网格,并获得生成的 z 网格。然后你可以绘制网格。

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    
    def z_func(x, y):
        z = 0.000855995633558468 * x ** 2 + 0.0102702516120239 * x + \
            0.00451027901725375 * y ** 2 - 2.23785431578513 * y + \
            251.029058292935
        return z
    
    # Creates a 1D array of all possible x and y coordinates
    x_coords = np.linspace(-30, 30, 100)
    y_coords = np.linspace(180, 220, 100)
    
    # Creates 2D array with all possible combinations of x and y coordinates,
    # so x_grid.shape = (100, 100) and y_grid.shape = (100, 100)
    [x_grid, y_grid] = np.meshgrid(x_coords, y_coords)
    
    # Evaluates z at all grid points
    z_grid = z_func(x_grid, y_grid)
    
    # Plotting
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x_grid,y_grid,z_grid)
    plt.show()
    

    【讨论】:

    • 谢谢!如果我想用坐标点绘制一条抛物线怎么办?
    • 我不是 100% 的你的意思。如果您想绘制一条曲线,如在单行中,您可以使用已有的代码,但您必须确保 x、y 和 z 数组中的坐标完全按照您希望的顺序排列要拥有的行。
    猜你喜欢
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多