【问题标题】:Output a centred HTML image with mpld3使用 mpld3 输出居中的 HTML 图像
【发布时间】:2021-03-31 23:31:09
【问题描述】:

我正在使用mpld3 Python 包将静态matplotlib 图形保存为html 格式的交互式图像。一个简单的例子如下:

# draw a static matplotlib figure
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x))

# save as an interactive html file
import mpld3

html_str = mpld3.fig_to_html(fig)
Html_file= open("sample.html","w")
Html_file.write(html_str)
Html_file.close()

但问题是当在浏览器中打开 html 图片时,它总是在左上角。有没有办法让它居中,甚至可以更好地控制输出样式?

【问题讨论】:

  • 那为什么不用css将html居中呢?
  • @BijayRegmi 谢谢,我看到一些提到 css 的帖子,但我没有这方面的背景。我几乎只将 Python 用于研究计算。所以我想不出一个css解决方案。
  • 然后发布一个示例,说明“sample.html”的外观并将标签更改为 HTML 和 CSS

标签: html css python-3.x matplotlib mpld3


【解决方案1】:

mpld3.fig_to_html() 只是生成一段 html 片段。虽然单独的片段可以作为 html 文档工作,但它应该被嵌入到完整的 html 文档中。

以下是使用figid 选项为生成的片段指定id fig1 的解决方案示例。为 id 为 fig1<div> 准备带有 CSS 样式定义的 html 文档。并将片段嵌入到文档中。

html_fragment = mpld3.fig_to_html(fig, figid = 'fig1')

html_doc = f'''
<style type="text/css">
div#fig1 {{ text-align: center }}
</style>

{html_fragment}
'''

Html_file= open("sample.html","w")
Html_file.write(html_doc)
Html_file.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2011-11-15
    • 1970-01-01
    相关资源
    最近更新 更多