问题
I'm creating a 3D scatter plot with multiple sets of data and using a colormap for the whole figure. The code looks like this:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for R in [range(0,10), range(5,15), range(10,20)]:
data = [np.array(R), np.array(range(10)), np.array(range(10))]
AX = ax.scatter(*data, c=data[0], vmin=0, vmax=20, cmap=plt.cm.jet)
def forceUpdate(event): AX.changed()
fig.canvas.mpl_connect('draw_event', forceUpdate)
plt.colorbar(AX)
This works fine but as soon as I save it or rotate the plot, the colors on the first and second scatters turn blue.

The force update is working by keeping the colors but only on the last scatter plot drawn. I tried making a loop that updates all the scatter plots but I get the same result as above:
AX = []
for R in [range(0,10), range(5,15), range(10,20)]:
data = [np.array(R), np.array(range(10)), np.array(range(10))]
AX.append(ax.scatter(*data, c=data[0], vmin=0, vmax=20, cmap=plt.cm.jet))
for i in AX:
def forceUpdate(event): i.changed()
fig.canvas.mpl_connect('draw_event', forceUpdate)
Any idea how I can make sure all scatters are being updated so the colors don't disappear?
Thanks!
回答1:
Having modified your code so that it does anything:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from mpl_toolkits.mplot3d import Axes3D
>>> AX = \[\]
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111, projection='3d')
>>> for R in \[range(0,10), range(5,15), range(10,20)\]:
... data = \[np.array(R), np.array(range(10)), np.array(range(10))\]
... AX = ax.scatter(*data, c=data\[0\], vmin=0, vmax=20, cmap=plt.cm.jet)
... def forceUpdate(event): AX.changed()
... fig.canvas.mpl_connect('draw_event', forceUpdate)
...
9
10
11
>>> plt.colorbar(AX)
<matplotlib.colorbar.Colorbar instance at 0x36265a8>
>>> plt.show()
then I get:

So the above code is working. If your existing code isn't then I suggest that you try the exact code above and if that doesn't work look into the versions of code that you are using if it does work then you will have to investigate the differences between it and your actual code, (rather than your example code).
来源:https://stackoverflow.com/questions/18238330/python-3d-scatter-losing-colormap