1

I would like to add colors to my labels in the legend of 3D plot, but is not working when I tried with a similar method to add colors to a regular plt.plot.

fig = plt.figure(figsize=(10, 8))
ax = Axes3D(fig)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', 'tab:blue', 'tab:orange', 
'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:olive', 'tab:cyan', 'yellow', 'tomato']

ax.scatter(xs=xs_valence, ys=ys_arousal, zs=zs_dominance, zdir='z', s=len(xs_valence), c=colors, label=labels_df_labels)
ax.legend()
plt.grid(b=True)
plt.show()

Expected output should contain colors in the legend to each label.

3Dplot

What I tried:

fig = plt.figure(figsize=(10, 8))
ax = Axes3D(fig)

scatter = ax.scatter(xs=xs_valence, ys=ys_arousal, zs=zs_dominance, zdir='z', s=len(xs_valence), cmap='Spectral')

X_cmap = .7
kw = dict(prop='colors', num=len(xs_valence), color=scatter.cmap(X_cmap), fmt='{x}', func=lambda s: [s for s in labels_df_labels])

legend1 = ax.legend(*scatter.legend_elements(**kw), loc='upper left', title='Labels')

ax.add_artist(legend1)
plt.show()

Also:

fig = plt.figure(figsize=(10, 8))
ax = Axes3D(fig)

for idx, row in df_labels.iterrows():
    color = row['colors']
    label = row['Labels']
    xs_valence, ys_arousal, zs_dominance = row['Valence'], row['Arousal'], row['Dominance']
    
    ax.plot(xs=xs_valence,
            ys=ys_arousal, 
            zs=zs_dominance, 
            zdir='z',
            s=18, 
            label=label, 
            color=color)

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))
plt.show()

TypeError                                 Traceback (most recent call last)
<ipython-input-139-4e34b382128f> in <module>()
     13             s=18,
     14             label=label,
---> 15             color=color)
     16 
     17 plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

/usr/local/lib/python3.6/dist-packages/mpl_toolkits/mplot3d/axes3d.py in plot(self, xs, ys, zdir, *args, **kwargs)
   1419 
   1420         # Match length
-> 1421         zs = np.broadcast_to(zs, len(xs))
   1422 
   1423         lines = super().plot(xs, ys, *args, **kwargs)

TypeError: object of type 'float' has no len()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Y4RD13
  • 937
  • 1
  • 16
  • 42

1 Answers1

1

I don't think it makes a difference that the data are stored in a pandas dataframe. In 2D, you could transform your data and use pandas plotting wrapper that tries to guess a lot of matplotlib parameters (including the label of a data series). However, this is a 3D plot, which is imho not supported by pandas plotting. So, back to the old zip approach:

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

#simulate your data
np.random.seed(123)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', 'tab:blue', 'tab:orange', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:olive', 'tab:cyan', 'yellow', 'tomato']
df = pd.DataFrame({"Valence": np.random.random(len(colors)), 
                   "Arousal": np.random.random(len(colors)), 
                   "Dominance": np.random.random(len(colors)),
                   "colors": colors,
                   "Labels": [f"{i}: {c}" for i, c in enumerate(colors)]
                   })

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(projection='3d')
 
for x, y, z, c, l in zip(df.Valence, df.Arousal, df.Dominance, df.colors, df.Labels):
    ax.scatter(xs=x, ys=y, zs=z, s=40, c=c, label=l)

ax.legend(ncol=3)
plt.grid(b=True)
plt.show()

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Mr. T
  • 11,960
  • 10
  • 32
  • 54