CSY
CSY

Reputation: 151

Matplotlib scatter plot failed to display all legends (some are missing)

In my data, they are 23 classes in total.

all_classes = ['E6Tle4', 'E2Rasgrf2', 'InV', 'E4Thsd7a', 'E3Rmst', 'E3Rorb','E5Galnt14', 'Clau', 'E4Il1rapl2', 'E5Parm1', 'OPC', 'Mis', 'E5Sulf1', 'Ast', 'OliM', 'E5Tshz2', 'InS', 'InN', 'InP', 'OliI', 'Endo', 'Mic', 'Peri']

I want to make scatter plots for points with these classes as label. However, the legend only showed 9 classes. Here is a toy example to reproduce the err.

a = np.random.rand(23)/23
size= 2000
df = pd.DataFrame(
    {'x': np.random.rand(size),
    'y': np.random.rand(size),
     'classes': np.random.choice(all_classes, size, p=a/sum(a))
    })
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df["label"] = le.fit_transform(df["classes"])

fig, axes = plt.subplots(1, 3, figsize=(10,3))
fig.suptitle("true label")
ax1 = axes[0]
vis(ax1, df, df["label"], df["classes"], title="RNA")
fig.tight_layout()
fig.subplots_adjust(top=0.85)


def vis(ax, df, label_num, label_name, alpha=0.7, s=10, title="visualization", vis=False):
    points = ax.scatter(df.iloc[:, 0], df.iloc[:, 1], c=label_num, label=label_name, edgecolor='none',alpha=0.7, s=s)
    ax.spines["top"].set_visible(vis)
    ax.spines["right"].set_visible(vis)
    ax.set_title(title)
    
    ax.legend(handles=points.legend_elements()[0], labels=list(np.unique(label_name)), 
              title="Classes", loc='center left', bbox_to_anchor=(1, 0.5))

Using the following code we can confirm that the column classes contains 23 classes.

len(df["classes"].unique())  # return 23

enter image description here

However, you can see that only 9 classes are shown in the legend.

Upvotes: 3

Views: 1365

Answers (1)

Tom
Tom

Reputation: 8800

You can set the num parameter in the handles=points.legend_elements()[0] call:

ax.legend(handles=points.legend_elements(num=len(all_classes))[0],...)

enter image description here

You'll need to edit the sizes of course, say with a single axes of figsize = (7,7) you get:

enter image description here

See the documentation here (which granted is kind of tucked away). I guess by default the parameter is set to num="auto" which is vaguely automatic, but seems like it just sets a cutoff which is fine for most datasets.

Upvotes: 5

Related Questions