python变量图片_在Python中向3D图添加第4个变量

Matplotlib允许将facecolors作为参数传递给例如

ax.plot_surface.

这意味着您必须在自己的电脑上执行2D插值

当前的颜色数组,因为您当前仅在

矩形面的角(您确实提到您有一个直线

格).

给你一个简单的例子:

import numpy as np

y,x = np.mgrid[1:10:10j, 1:10:10j] # returns 2D arrays

# You have 1D arrays that would make a rectangular grid if properly reshaped.

y,x = y.ravel(), x.ravel() # so let's convert to 1D arrays

z = x*(x-y)

colors = np.cos(x**2) - np.sin(y)**2

现在,我有一个与您相似的数据集(x,y,z和

颜色).请注意,颜色是为

每个点(x,y).但是,当您要使用plot_surface进行绘制时,

生成矩形斑块,其角由那些点给出.

因此,接着进行插值:

from scipy.interpolate import RectBivariateSpline

# from scipy.interpolate import interp2d # could 've used this too, but docs suggest the faster RectBivariateSpline

# Define the points at the centers of the faces:

y_coords, x_coords = np.unique(y), np.unique(x)

y_centers, x_centers = [ arr[:-1] + np.diff(arr)/2 for arr in (y_coords, x_coords)]

# Convert back to a 2D grid, required for plot_surface:

Y = y.reshape(y_coords.size, -1)

X = x.reshape(-1, x_coords.size)

Z = z.reshape(X.shape)

C = colors.reshape(X.shape)

#Normalize the colors to fit in the range 0-1, ready for using in the colormap:

C -= C.min()

C /= C.max()

interp_func = RectBivariateSpline(x_coords, y_coords, C.T, kx=1, ky=1) # the kx, ky define the order of interpolation. Keep it simple, use linear interpolation.

在最后一步中,您可能还已经使用过interp2d(with kind =’linear’

替换kx = 1,ky = 1).但是由于文档建议使用更快

RectBivariateSpline …

现在您可以绘制它了:

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.cm as cm

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

r = ax.plot_surface(X,Y,Z,

facecolors=cm.hot(interp_func(x_centers, y_centers).T),

rstride=1, cstride=1) # only added because of this very limited dataset

如您所见,面上的颜色与数据集的高度无关.

请注意,您可能以为只需将2D数组C传递给facecolors就可以了,而matplotlib不会抱怨.但是,结果是不准确的,因为matplotlib将仅使用C的一部分作为面色(它似乎忽略了C的最后一列和最后一行).这等效于仅使用由整个色块中一个坐标(例如,左上角)定义的颜色.

一种更简单的方法是让matplotlib进行插值并获取facecolor,然后将其传递给实际图:

r = ax.plot_surface(X,Y,C, cmap='hot') # first plot the 2nd dataset, i.e. the colors

fc = r.get_facecolors()

ax.clear()

ax.plot_surface(X, Y, Z, facecolors=fc)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值