简体   繁体   中英

matplotlib pcolor not working when used as “2D plot in 3D”

I am trying to add a pcolor plot to the example code given here http://matplotlib.org/examples/mplot3d/2dcollections3d_demo.html

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

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

x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')

colors = ('r', 'g', 'b', 'k')
for c in colors:
    x = np.random.sample(20)
    y = np.random.sample(20)
    ax.scatter(x, y, 0, zdir='y', c=c)

xc = np.linspace(0, 1, 100)
yc = np.linspace(0, 1, 100)
fc = np.random.random((len(xc),len(yc)))
ax.pcolor(xc,yc,fc, zdir = 'x')

ax.legend()
ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 1)
ax.set_zlim3d(0, 1)

plt.show()

Just few new lines when compared to the original script. Unfortunately, it doesn't end well and I really don't understand why.

Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/artist.py", line 61, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/figure.py", line 1159, in draw
    func(*args)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 271, in draw
    for col in self.collections]
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 271, in <listcomp>
    for col in self.collections]
AttributeError: 'PolyCollection' object has no attribute 'do_3d_projection'

Thank you all for the support.

It is not clear what you want to achieve. There is a 3D plot in the example but pcolor is a 2D plot. You can't add a pcolor plot to the 3D plot, that's why you get the error, so add a new figure:

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

x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')

colors = ('r', 'g', 'b', 'k')
for c in colors:
    x = np.random.sample(20)
    y = np.random.sample(20)
    ax.scatter(x, y, 0, zdir='y', c=c)

ax.legend()
ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 1)
ax.set_zlim3d(0, 1)


fig = plt.figure()
xc = np.linspace(0, 1, 100)
yc = np.linspace(0, 1, 100)
fc = np.random.random((len(xc),len(yc)))
plt.pcolor(xc,yc,fc,cmap='RdBu')
plt.colorbar() 

pcolor has no attribute zdir , so you need to adjust the order of xc,yc,fc in the right way, depending on what you actually want to see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM