How to add a legend in a pandas DataFrame scatter plot?

sK500 :

I have a pandas DataFrame that contains the following columns of interest:

['Relative Width', 'Relative Height', 'Object Name', 'Object ID']

There are 15 object names with 15 colors determined with df.plot(c='Object ID') that produce the following figure:

fig

I want to display a legend with the 15 object names, how this can be done?

import matplotlib.pyplot as plt
from annotation_parsers import parse_voc_folder


def visualize_box_relative_sizes(folder_path, voc_conf, cache_file='data_set_labels.csv'):
    frame = parse_voc_folder(folder_path, voc_conf, cache_file)
    title = f'Relative width and height for {frame.shape[0]} boxes.'
    frame.plot(
        kind='scatter',
        x='Relative Width',
        y='Relative Height',
        title=title,
        c='Object ID',
        colormap='gist_rainbow',
        colorbar=False,
    )
    plt.show()

Based on wwnde recommendation, I changed the code to the following:

def visualize_box_relative_sizes(folder_path, voc_conf, cache_file='data_set_labels.csv'):
    frame = parse_voc_folder(folder_path, voc_conf, cache_file)
    title = f'Relative width and height for {frame.shape[0]} boxes.'
    sns.scatterplot(x=frame["Relative Width"], y=frame["Relative Height"], hue=frame["Object Name"])
    plt.title(title)
    plt.show()

which produces the following result:

enter image description here

wwnde :

Please Try

fig, ax = plt.subplots()

ax = sns.scatterplot(x="total_bill", y="tip",
                     hue="size", size="size",
                     data=tips)
ax.set_title('title')
plt.show()

This should give you a default coloured legend

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371795&siteId=1