首页 > 解决方案 > 在 Jupyter Notebooks 中呈现交互式 Pygal 图表

问题描述

我试图在 Jupyter Notebook 中渲染交互式 Pygal 图表,但没有成功。我不是在寻找效果很好的图像静态版本解决方案,而是寻找具有交互式工具提示的解决方案。

这个问题之前已经解决了:

但不幸的是,没有人遇到我的问题:实现这些链接中提供的解决方案 Jupyter 似乎无法正确呈现图表,而是输出是一个非常长的字符串。不会产生错误。

我错过了什么?

标签: pythonchartsjupyter-notebookrenderpygal

解决方案


我不会假装理解为什么,但切换到 Unicode 字符串可以解决问题。这可能是很少有人遇到这个问题的原因:在 Python 3 中,默认情况下所有字符串都是 Unicode。

您需要通过在字符串前面加上前缀来将模板声明为 Unicode 文字u。然后通过is_unicode=True作为参数传递给render函数来告诉 pygal 在渲染图表时返回 Unicode。

一个例子:

from IPython.display import HTML
import pygal

html_pygal = u"""
    <!DOCTYPE html>
    <html>
        <head>
            <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/svg.jquery.js"></script>
            <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/pygal-tooltips.js"></script>
        </head>
        <body><figure>{pygal_render}</figure></body>
    </html>
"""

line_chart = pygal.Line()
line_chart.title = "Browser usage evolution (in %)"
line_chart.x_labels = map(str, range(2002, 2013))
line_chart.add("Firefox", [None, None, 0, 16.6, 25, 31, 36.4, 45.5, 46.3, 42.8, 37.1])
line_chart.add("Chrome", [None, None, None, None, None, None, 0, 3.9, 10.8, 23.8, 35.3])
line_chart.add("IE", [85.8, 84.6, 84.7, 74.5, 66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])
line_chart.add("Others", [14.2, 15.4, 15.3, 8.9, 9, 10.4, 8.9, 5.8, 6.7, 6.8, 7.5])
HTML(html_pygal.format(pygal_render=line_chart.render(is_unicode=True)))

推荐阅读