在 python seaborn 图中创建多列图例 [英] Creating multi column legend in python seaborn plot
问题描述
我正在使用 seaborn.distplot
(python3) 并且希望每个系列有 2 个标签.
I am using seaborn.distplot
(python3) and want to have 2 labels for each series.
我尝试了一种像这样的hacky字符串格式方法:
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
我假设图中使用的字体不是固定宽度,所以我想知道是否有一种方法可以指定我的图例以具有 2 个对齐列的标签,并且可能调用 seaborn.distplot
,其中带有 label
kwarg的 tuple
(或其他可行方法).
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).
我的情节供参考:
看起来不错,但我确实希望每个系列的2个标签以某种方式对齐.
Looks good but I really want the 2 labels per series aligned somehow.
推荐答案
这不是一个好的解决方案,但希望是一个合理的解决方法.关键思想是将图例分为3列以进行对齐,使第2列和第3列的图例手柄不可见,并在第3列的右侧对齐.
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()
这篇关于在 python seaborn 图中创建多列图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!