Scatter3D: Error When Specifying Color and Alpha as Iterables in Matplotlib if Label Added

Viewed 110

I am trying to vary opacity on each marker in a 3D scatter plot. I hit an issue with this where it was saying the color was not the correct length (even though it was). Moving to the simplest case it can be recreated with this.

import matplotlib.pyplot as plt
import numpy as np


fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
elements = 100
x = np.linspace(0, 10, elements)

ax.scatter(x, x, x, alpha=np.linspace(1, 0.5, elements), c=['b' for _ in range(elements)], label='label')
fig.legend()

plt.show()

If the label keyword argument is removed it works. If you do a 2D scatter plot it works regardless of the label. I am wondering if this is a bug but wanted to see if I was missing something first.

1 Answers

To accomplish what you want, try to use set_facecolors instead of directly using the alpha and color in the scatter plot.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
elements = 200

z = np.linspace(0, 2*np.pi, elements)
x = np.cos(z)
y = np.sin(z)

h = ax.scatter(x, y, z, label='label')
h.set_facecolors([[0., 0., 1., alpha] for alpha in np.linspace(0.1, 0.7, len(x))])

fig.legend()
plt.show()

spiral_scatter_plot

Related