Skip to content Skip to sidebar Skip to footer

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 m

Solution 1:

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 inrange(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

Post a Comment for "Creating Multi Column Legend In Python Seaborn Plot"