在Python中将2D图形转换为圆柱体

时间:2016-04-16 20:28:56

标签: python matplotlib

目前我的数字看起来像enter image description here

由代码生成:

import matplotlib.pyplot as plt

import numpy as np

data = np.random.rand(20,5)
rows,cols = data.shape

plt.imshow(data, interpolation='nearest', extent=[0.5, 0.5+cols, 0.5,   0.5+cols], cmap='bwr')
plt.show()

但是我想折叠'这就是一个3D圆柱体,连接左右边缘(就像一张纸一样)。换句话说,左边缘和右边缘实际上是相同的边缘,所以我想将它们连接在一起形成圆柱体。

我将如何做到这一点?

2 个答案:

答案 0 :(得分:3)

Poly3DCollectionmplot3d中任意3D多边形的首选方法。

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

fig = plt.figure()
ax = fig.gca(projection='3d')

nphi,nz=12,20
r=1 # radius of cylinder
phi = np.linspace(0,360, nphi)/180.0*np.pi
z= np.linspace(0,1.0,nz)
print z

facecolors=['r','g','b','y']
cols=[]
verts2 = []
for i  in range(len(phi)-1):
    cp0= r*np.cos(phi[i])
    cp1= r*np.cos(phi[i+1])
    sp0= r*np.sin(phi[i])
    sp1= r*np.sin(phi[i+1])

    for j in range(len(z)-1):
        z0=z[j]
        z1=z[j+1]
        verts=[]
        verts.append((cp0, sp0, z0))
        verts.append((cp1, sp1, z0))
        verts.append((cp1, sp1, z1))
        verts.append((cp0, sp0, z1))
        verts2.append(verts)
        value=np.random.rand()
        print value
        col=plt.cm.bwr(value)
        print col
        cols.append(col)

poly3= Poly3DCollection(verts2, facecolor=cols  )  

poly3.set_alpha(0.8)
ax.add_collection3d(poly3)
ax.set_xlabel('X')
ax.set_xlim3d(-1, 1)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 1)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)
plt.show()

enter image description here

答案 1 :(得分:0)

您可以使用plot_surface

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

np.random.seed(2016)
data = np.random.rand(12, 20)
h, w = data.shape
theta, z = np.linspace(0, 2 * np.pi, w), np.linspace(0, 1, h)
THETA, Z = np.meshgrid(theta, z)    
X = np.cos(THETA)
Y = np.sin(THETA)

fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
cmap = plt.get_cmap('bwr')
plot = ax.plot_surface(
    X, Y, Z, rstride=1, cstride=1, facecolors=cmap(data),
    linewidth=0, antialiased=False, alpha=0.75)

plt.show()

产量

enter image description here