Matplotlib 3D散点图_facecolors3d不起作用

问题描述

我正在尝试保存3D散点图动画,其中点一次出现一次。我制作了动画,但是当我设置点的面色时它们不会生效,所有点都显示为蓝色。当我在静态图像上使用相同的颜色阵列时,颜色效果很好。

动画代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation
import random
import seaborn as sns
import pandas as pd
import json
import os
from matplotlib.animation import FuncAnimation
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib import rc
from IPython.display import HTML
from itertools import product

x=[]
y=[]

for i in range(-80,80,10):
    x.append(i)
    y.append(i)

combs = list(product(x,y))
def obj(x,y):
    global HISTORY
    e = 2.718
    res = 7*x*y/(e**(0.001*x**2 + 0.001*y**2))
    return res
z = [obj(x,y) for x,y in combs]
x = [obj[0] for obj in combs]
y = [obj[1] for obj in combs]

data = [[x[i],y[i],z[i]] for i in range(len(x))]
cmap = sns.cubehelix_palette(as_cmap=True)
m = max(z) # Get the worst score so we can use it as the darkest area of the plot.
face_colors = np.array([cmap(i/m) for i in z]) # Map all of the values with cmap colors. 
df = pd.DataFrame(data,columns=["x","y","z"])


fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
sc = ax.scatter([],[],alpha=0.5)

def update(i):
    sc._offsets3d = (df.x.values[:i],df.y.values[:i],df.z.values[:i])
    sc._facecolors3d = face_colors[:i]
    sc._facecolors2d=sc._facecolors3d

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(min(x),max(x))
ax.set_ylim(min(y),max(y))
ax.set_zlim(min(z),max(z))

ani = matplotlib.animation.FuncAnimation(fig,update,frames=len(df),interval=70)
HTML(ani.to_html5_video())

enter image description here

当我不使用动画时,只需要像这样调用plt.scatter:

sc = ax.scatter(df.x.values,df.y.values,df.z.values,facecolors=face_colors)

我的图像效果很好:

enter image description here

如何在动画中保留这些颜色?

静态图片代码

x=[]
y=[]

for i in range(-80,z[i]] for i in range(len(x))]
cmap = sns.cubehelix_palette(as_cmap=True)
m = max(z) # Get the worst score so we can use it as the darkest area of the plot.
face_colors = [cmap(i/m) for i in z] # Map all of the values with cmap colors. 
df = pd.DataFrame(data,projection='3d')
sc = ax.scatter(df.x.values,facecolors=face_colors)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(min(x),max(z))

plt.show()

解决方法

可能只是一个错字。 _facecolor3d代替_facecolors3d,请尝试以下操作:

def update(i):
    sc._offsets3d = (df.x.values[:i],df.y.values[:i],df.z.values[:i])
    sc._facecolor3d = face_colors[:i]
    sc._edgecolor3d = face_colors[:i]