Skip to content Skip to sidebar Skip to footer

How To Change Legend Text When Plotting 3d Scatter Plot With Matplotlib?

I have a 3D scatter plot which was produced using the following code import seaborn as sns import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import

Solution 1:

The code can be simplified making use of pandas to do conversions and selections. By drawing the scatter plot for each 'name' separately, they each can be given a label for the legend.

Here is the adapted code:

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

# Create an example dataframe
data = {'th': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2],
        'pdvalue': [0.5, 0.5, 0.5, 0.5, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.4, 0.1, 1, 1.1, 3, 1],
        'my_val': [1.2, 3.2, 4, 5.1, 1, 2, 5.1, 1, 2, 4, 1, 3, 6, 6, 2, 3],
        'name': ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']}
df = pd.DataFrame(data)

# axes instance
fig = plt.figure(figsize=(10, 6))
ax = Axes3D(fig, auto_add_to_figure=False)
fig.add_axes(ax)

# find all the unique labels in the 'name' column
labels = np.unique(df['name'])
# get palette from seaborn
palette = sns.color_palette("husl", len(labels))

# plotfor label, color inzip(labels, palette):
    df1 = df[df['name'] == label]
    ax.scatter(df1['th'], df1['pdvalue'], df1['my_val'],
               s=40, marker='o', color=color, alpha=1, label=label)
ax.set_xlabel('th')
ax.set_ylabel('pdvalue')
ax.set_zlabel('my_val')

# legend
plt.legend(bbox_to_anchor=(1.05, 1), loc=2)
plt.show()

3d scatter plot with legend

Post a Comment for "How To Change Legend Text When Plotting 3d Scatter Plot With Matplotlib?"