Python: 3D scatter losing colormap

最后都变了- 提交于 2019-12-08 09:39:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!