Skip to main content
 首页 » 编程设计

python之中心嵌入式 Bokeh 图

2025年04月02日14zhoujg

如何让嵌入的 Bokeh 图居中?我的 css 似乎对 Bokeh 的 <div class="plotdiv"> 没有影响.在下面的最小示例中,我希望绘图位于黄色容器的中心。

from jinja2 import Template 
from bokeh.embed import components 
from bokeh.models import Range1d 
from bokeh.plotting import figure 
from bokeh.resources import INLINE 
from bokeh.util.browser import view 
 
x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
y1 = [0, 8, 2, 4, 6, 9, 5, 6, 25, 28, 4, 7] 
 
p1 = figure(plot_width=300, plot_height=300) 
p1.scatter(x1, y1, size=12, color="red", alpha=0.5) 
 
script, div = components(p1) 
 
template = Template('''<!DOCTYPE html> 
<html lang="en"> 
    <head> 
        <meta charset="utf-8"> 
        <title>Bokeh Scatter Plots</title> 
        {{ js_resources }} 
        {{ css_resources }} 
        {{ script }} 
    <style> 
    .wrapper { 
        width: 800px; 
        background-color: yellow; 
        margin: 0 auto; 
        } 
 
    .plotdiv { 
        margin: 0 auto; 
        } 
    </style> 
    </head> 
    <body> 
    <div class='wrapper'> 
        {{ div }} 
    </div> 
    </body> 
</html> 
''') 
 
js_resources = INLINE.render_js() 
css_resources = INLINE.render_css() 
 
filename = 'embed_multiple.html' 
 
html = template.render(js_resources=js_resources, 
                       css_resources=css_resources, 
                       script=script, 
                       div=div) 
 
with open(filename, 'w') as f: 
    f.write(html) 
 
view(filename) 

** 下面的填充只是为了安抚SE的机器人**

SE 的机器人要我添加“更多细节”,因为这个问题“主要是代码”。嘿,机器人,问题很简单,它只是“主要是代码”,因为我做了功课,并试图让人们更容易帮助我。

请您参考如下方法:

带有 Bokeh 0.11.1更改为以下对我有用:

.bk-plot-wrapper table { 
    margin: 0 auto; 
} 

问题是 div.bk-plot-wrapper占用了封闭空间的所有空间 <div> .但是内部<table>说明情节没有。我不是 CSS 专家,但也许其他人可以添加更多信息

两个注意事项:我不确定您使用的是哪个版本的 Bokeh,.plotdiv已经有一段时间没有使用了。另请注意,布局的一些基础改进将在 0.12 中着陆。使 Bokeh 在默认情况下更具响应性和“webby”,因此上面的代码可能不适用于 0.12 (特别是,<table> 即将消失)。