spanishgum
spanishgum

Reputation: 1060

Creating multi column legend in python seaborn plot

I am using seaborn.distplot (python3) and want to have 2 labels for each series.

I tried a hacky string format method like so:

# bigkey and bigcount are longest string lengths of my keys and counts
label = '{{:{}s}} - {{:{}d}}'.format(bigkey, bigcount).format(key, counts['sat'][key])

In the console where text is fixed width, I get:

(-inf, 1)  -   2538
[1, 3)     -   7215
[3, 8)     -  40334
[8, 12)    -  20833
[12, 17)   -   6098
[17, 20)   -    499
[20, inf)  -     87

I am assuming the font used in the plot is not fixed width, so I want to know if there is a way I can specify my legend to have labels with 2 aligned columns, and perhaps call seaborn.distplot with a tuple for the label kwarg (or whatever works).

My plot for reference:

enter image description here

Looks good but I really want the 2 labels per series aligned somehow.

Upvotes: 4

Views: 2794

Answers (1)

Y. Luo
Y. Luo

Reputation: 5722

This is not a good solution, but hopefully a reasonable workaround. The key idea is to split legend into 3 column for aligning purpose, make legend handles on column 2 and 3 invisible and align the column 3 on its right.

import io

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

x = np.random.randn(100)
s = [["(-inf, 1)", "-", 2538],
     ["[1, 3)", "-", 7215],
     ["[3, 8)", "-", 40334],
     ["[8, 12)", "-", 20833],
     ["[12, 17)", "-", 6098],
     ["[17, 20)", "-", 499],
     ["[20, inf)", "-", 87]]

fig, ax = plt.subplots()
for i in range(len(s)):
    sns.distplot(x - 0.5 * i, ax=ax)

empty = matplotlib.lines.Line2D([0],[0],visible=False)
leg_handles = ax.lines + [empty] * len(s) * 2
leg_labels = np.asarray(s).T.reshape(-1).tolist()
leg = plt.legend(handles=leg_handles, labels=leg_labels, ncol=3, columnspacing=-1)
plt.setp(leg.get_texts()[2 * len(s):], ha='right', position=(40, 0))

plt.show()

enter image description here

Upvotes: 5

Related Questions