首页 > 解决方案 > 绘制多个点

问题描述

我有一个 matplotlib 曲面,我需要在该曲面上绘制一组点。下面是我必须创建表面的代码:

import numpy as np
import matplotlib.pyplot as plt

def graficar(fun):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    x = y = np.arange(-1.0, 1.0, 0.05)
    X, Y = np.meshgrid(x, y)
    zs = np.array(fun(np.ravel(X), np.ravel(Y)))
    Z = zs.reshape(X.shape) 
    ax.plot_surface(X, Y, Z)
    title='Graficación de la función'
    ax.set_title(title)
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    plt.show()

#funcion x**2 + y**2
def funcion1(x, y):
    return (x)**2 + (y)**2

graficar(funcion1)

在创建的曲面上,我需要绘制点,例如 (-3, 3)、(-2,2)、(-1, 1) 等。这些点需要显示在曲面本身上,所以我认为要做到这一点,我需要评估函数上的点,在我的示例中(在函数 funcion1 中定义)如果我评估点 (-2, 2),它将是 (-2)**2 + (2) **2 = 4 +4 = 8,所以点将是 x = -2,y = 2,z = 8,我需要在表面上显示该点

我怎样才能做到这一点?

标签: pythonmatplotlibplot

解决方案


以下代码应该适合您:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import get_test_data
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

def randrange(n, vmin, vmax):
    '''
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin


def graficar(fun):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    x = y = np.arange(-1.0, 1.0, 0.05)
    X, Y = np.meshgrid(x, y)
    zs = np.array(fun(np.ravel(X), np.ravel(Y)))
    Z = zs.reshape(X.shape)
    ax.plot_surface(X, Y, Z)
    title = 'Graficación de la función'
    ax.set_title(title)
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    (xs, ys, zs) = ([0, 0.2, 1, 1.2, 0.3],
                    [-0.2, 0.3, 1.8, 0.7, 1.0], [1.0, 0.6, 0.4, 0.9, -0.5])
    ax.scatter(xs, ys, zs, c='r', marker='^')
    plt.show()

# funcion x**2 + y**2


def funcion1(x, y):
    return (x)**2 + (y)**2


graficar(funcion1)

这将为您提供以下情节:

从代码中绘制


推荐阅读