如何在Python

时间:2017-04-07 10:28:06

标签: python python-3.x plot

我有两个矩阵,我希望在同一个图上的两个子图上有相应的两个三维图,z轴相同。

到目前为止,这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D

def myplot(matrix1, matrix2):
    mymin = np.min(np.array([np.min(matrix1), np.min(matrix2)]))
    mymax = np.max(np.array([np.max(matrix1), np.max(matrix2)]))

    xsize, ysize = matrix1.shape
    x = np.arange(0, ysize, 1)
    y = np.arange(0, xsize, 1)

    xs, ys = np.meshgrid(x, y)
    z1 = matrix1
    z2 = matrix2

    fig, (ax1, ax2) = plt.subplots(1, 2)
    ax1 = Axes3D(fig)
    ax1.plot_surface(xs, ys, z1, rstride=1, cstride=1)
    ax2 = Axes3D(fig)
    ax2.plot_surface(xs, ys, z2, rstride=1, cstride=1)
    plt.tight_layout
    plt.show()

mat1 = np.random.random(size = (10, 10))
mat2 = np.random.random(size = (10, 10))

myplot(mat1, mat2)
  • 为什么我只看到一个3D情节?
  • 如何在两个图中都有相同的z轴?

1 个答案:

答案 0 :(得分:3)

我认为您需要生成子图

见下图(我也改变了颜色)

def myplot(matrix1, matrix2):
    mymin = np.min(np.array([np.min(matrix1), np.min(matrix2)]))
    mymax = np.max(np.array([np.max(matrix1), np.max(matrix2)]))

    xsize, ysize = matrix1.shape
    x = np.arange(0, ysize, 1)
    y = np.arange(0, xsize, 1)

    xs, ys = np.meshgrid(x, y)
    z1 = matrix1
    z2 = matrix2
    fig=plt.figure()
    ax1 = fig.add_subplot(2, 1, 1, projection='3d')
    ax1.plot_surface(xs, ys, z1,color="blue",alpha=0.5,rstride=1, cstride=1)
    ax2 = fig.add_subplot(2, 1, 2, projection='3d')
    ax2.plot_surface(xs, ys, z2,color="green",alpha=0.5, rstride=1, cstride=1)
    plt.tight_layout
    plt.show()

mat1 = np.random.random(size = (10, 10))
mat2 = np.random.random(size = (10, 10))

myplot(mat1, mat2)

enter image description here

修改 要将myminmymax强加为两个z轴的限制,请使用

ax1.set_zlim(mymin, mymax)
ax2.set_zlim(mymin, mymax)