【问题标题】:How to prevent legend being truncated in bokeh?如何防止图例在散景中被截断?
【发布时间】:2021-06-17 08:22:04
【问题描述】:

这是一个简短的 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])

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

【问题讨论】:

    标签: python bokeh legend


    【解决方案1】:

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

    输出

    你的例子

    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 上有一个开放的功能请求,其中提到了这个解决方案。

    【讨论】:

    • 这是一个很好的解决方法,所以我很喜欢它。我不会接受它作为答案,以防几个月后功能请求得到满足,并且可以以某种方式扩展裁剪图例的边界框,以便可以完整地看到它。但这肯定会让我上路,所以谢谢你!
    • 另一条评论,以防有人过来。在一个案例中,我在一个图表中添加了 24 个图例,然后整个图表就消失了。这似乎是因为图例占用了图形域中的空间,并且必须缩小以使图例适合。一旦它缩小到某个点以上,整个事物(图形+图例)就会完全消失。解决方案是在图形宽度上添加一个任意数字(由实验确定),如下所示:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多