Creating a multi-column legend in a python offshore section
I am using seaborn.distplot
(python3) and want to have 2 labels for each series.
I've tried using the hacker strings 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 the 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 graphics is not a fixed width, so I want to know if there is a way that I can specify my legend to have labels with two aligned columns, and possibly call seaborn.distplot
with tuple
for label
kwarg (or what something works).
My plot for reference:
Looks good, but I really want the 2 labels for each series to line up somehow.
source to share
This is not a good solution, but hopefully a sane solution. The basic idea is to split the legend into 3 columns to align the target, make the descriptors on columns 2 and 3 invisible, and align column 3 to the 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()
source to share