python - 在 python seaborn plot 中创建多列图例

标签 python matplotlib seaborn

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

我尝试了一个像这样的 hacky 字符串格式方法:

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

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

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

我假设图中使用的字体不是固定宽度的,所以我想知道是否有一种方法可以指定我的图例具有带有 2 个对齐列的标签,并且可能调用 seaborn.distplot 带有 tuple 用于 label kwarg(或任何有效的)。

我的剧情供引用:

enter image description here

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

最佳答案

这不是一个好的解决方案,但希望是一个合理的解决方法。关键思想是为了对齐目的将图例分成 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

关于python - 在 python seaborn plot 中创建多列图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834508/

相关文章:

python - 通过配置文件创建函数实例

python - 关闭 Flask SocketIO 服务器

python - plot() 在 IPython notebook 上不起作用

colors - 如何反转Seaborn热图颜色条的颜色

python - 如何修改seaborn fiddle 图例

python - 从模块中导入带有其名称的子模块

python - 使用 django FORM 上传文件的唯一文件名

python - 将颜色图应用于 Matplotlib 3D 表面中的自定义轴

python - 如何设置子图 Axis 范围

python - 在 Seaborn 热图中将标题移动到颜色条上方