如何防止图例在散景中被截断?

时间:2021-03-19 22:37:50

标签: python bokeh legend

这是一个简短的 Python3 脚本,它用散景 (2.2.1) 绘制一堆正弦波。

import numpy
import bokeh.models
import bokeh.plotting

x    = numpy.linspace(0, 4*numpy.pi, 100)
sinx = numpy.sin(x)

bokeh.plotting.output_file("truncatedlegend.html")

plot = bokeh.plotting.figure(toolbar_location="above")

glyphs = [ plot.line(x, (1 + i/20)*sinx, line_width=2) for i in range(41) ]

legend = bokeh.models.Legend(
    items=[
        ("%.2f*sin(x)" % ((1 + i/20)), [ glyphs[i] ]) for i in range(41)
    ]
)

plot.add_layout(legend, 'right')

bokeh.plotting.show(plot)

图例应该有 40 个条目,但只有 24 个条目的空间,所以其余的都被扔掉了。我试着改变情节的边距,

    margin = plot.margin
    plot.margin = (margin[0], margin[1], margin[2] + 600, margin[3])

并且它确实增加了可用空间(因为第二个图(未显示)向下移动)---但图例没有扩展到可用空间。

1 个答案:

答案 0 :(得分:0)

这是我之前见过的其他一些关于 SO 的问题。共识是添加多个图例。

输出

two legends will do

你的榜样

import numpy
import bokeh.models
import bokeh.plotting

x    = numpy.linspace(0, 4*numpy.pi, 100)
sinx = numpy.sin(x)

bokeh.plotting.output_file("truncatedlegend.html")

plot = bokeh.plotting.figure(toolbar_location="above")
glyphs = [ plot.line(x, (1 + i/20)*sinx, line_width=2) for i in range(41) ]

legend1 = bokeh.models.Legend(
    items=[("%.2f*sin(x)" % ((1 + i/20)), [ glyphs[i] ]) for i in range(23)]
)
legend2 = bokeh.models.Legend(
    items=[("%.2f*sin(x)" % ((1 + i/20)), [ glyphs[i] ]) for i in range(23,41)]
)

plot.add_layout(legend1, 'right')
plot.add_layout(legend2, 'right')
bokeh.plotting.show(plot)

现在我在 SO 上找不到旧帖子。但是在提到此解决方案的 GitHub 上有一个开放的功能请求。