在pythonseaborn p中创建多列图例

2024-06-08 15:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是seaborn.distplot(python3),希望每个系列有2个标签。在

我尝试了一种简单的字符串格式方法,如下所示:

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

在文本为固定宽度的控制台中,我得到:

^{pr2}$

我假设绘图中使用的字体不是固定宽度的,所以我想知道是否有一种方法可以指定我的图例,使标签具有两个对齐的列,并可能使用tuple来调用labelkwarg(或任何有效的方法)。在

我的参考图:

enter image description here

看起来不错,但我真的希望每个系列的2个标签以某种方式对齐。在


Tags: and方法key字符串format宽度格式标签
1条回答
网友
1楼 · 发布于 2024-06-08 15:46:06

这不是一个好的解决方案,但希望是一个合理的解决办法。其关键思想是将图例拆分为3列以便对齐,使列2和列3上的图例句柄不可见,并将列3在其右侧对齐。在

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

相关问题 更多 >