【问题标题】:How to get python graph output into html webpage directly如何直接将python图形输出到html网页
【发布时间】:2018-08-07 12:43:09
【问题描述】:

我使用不同的库(如 pandas 和 numpy)来生成数据框,最终生成一个图表。

现在,我需要将此图表显示到一个简单的 HTML 网页中。

注意:我也愿意在 HTML 页面中从用户那里获取 2-3 个输入,然后将这些数据传递给我的 python 文件。之后,python 文件根据给定数据(来自 HTML 页面)生成一个图表,我需要将此图表传递给 HTML 页面。

df[[main_data]].plot()

这里,main_data 是变量,其值来自 HTML 页面。我正在 SPYDER 中编写 python 代码。 而且我没有使用任何框架。

【问题讨论】:

    标签: python html pandas graph


    【解决方案1】:

    这在一定程度上取决于您将图表显示为 html 的意思。我可以看到几种方法,第一种也是最简单的方法是将图形保存为 PNG,然后在 html 中提供文件的路径:

    Python 代码:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    s = pd.Series([1, 2, 3])
    fig, ax = plt.subplots()
    s.plot.bar()
    fig.savefig('my_plot.png')
    

    HTML:

    <img src='my_plot.png'/>
    

    第二种方法是将图形编码为base64。这具有可移植性的优点,以及制作非常大的笨重的html文件的缺点。我不是网络程序员,所以可能还有其他一些我不知道的警告。

    蟒蛇:

    import io
    import base64
    
    def fig_to_base64(fig):
        img = io.BytesIO()
        fig.savefig(img, format='png',
                    bbox_inches='tight')
        img.seek(0)
    
        return base64.b64encode(img.getvalue())
    
    encoded = fig_to_base64(fig)
    my_html = '<img src="data:image/png;base64, {}">'.format(encoded.decode('utf-8'))
    

    my_html 可以传递给你的 html 文件,或者你可以用 jinja2 或任何你使用的东西注入它。这是关于在 html https://stackoverflow.com/a/8499716/3639023 中查看 base64 并将图像编码为 base64 How to convert PIL Image.image object to base64 string?

    的帖子

    【讨论】:

    • 我也会尝试一下 graph.js 库。您可以使用请求库(或实现 Django 或 Flask 等框架)将数据从 python 传递到 HTML
    【解决方案2】:

    您也可以为此使用Plotly。这提供了更多interactive graphs。 您也可以将生成的数据写入HTML files, apply bootstrap styling

    查看this tutorial on their website

    【讨论】:

      【解决方案3】:

      您可能希望将图形保存到特定位置并编写脚本以读取图像文件,例如将pic.png 转换为HTML。对于输入,您可以创建一个Tabular 数据结构,并在每次输入后将数据保存到一个文件中,比如说file.csv 并在Python 中读取它并继续从输入中添加值。

      import matplotlib.pyplot as plt
      df.hist()
      plt.savefig('path/to/pic.png')
      

      现在创建 HTML 代码来读取该图像文件并根据需要输出它。我希望这会有所帮助。

      【讨论】:

        【解决方案4】:

        将 matplotlib 图表导出到 Web 浏览器的最佳方法是使用 mpld3 库。 这是示例。

        import matplotlib.pyplot as plt
        import numpy as np
        import pandas as pd
        import mpld3
        from mpld3 import plugins
        np.random.seed(9615)
        
        # generate df
        N = 100
        df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0),
                          columns=['a', 'b', 'c', 'd', 'e'],)
        
        # plot line + confidence interval
        fig, ax = plt.subplots()
        ax.grid(True, alpha=0.3)
        
        for key, val in df.iteritems():
            l, = ax.plot(val.index, val.values, label=key)
            ax.fill_between(val.index,
                            val.values * .5, val.values * 1.5,
                            color=l.get_color(), alpha=.4)
        
        # define interactive legend
        
        handles, labels = ax.get_legend_handles_labels() # return lines and labels
        interactive_legend = plugins.InteractiveLegendPlugin(zip(handles,
                                                                 ax.collections),
                                                             labels,
                                                             alpha_unsel=0.5,
                                                             alpha_over=1.5, 
                                                             start_visible=True)
        plugins.connect(fig, interactive_legend)
        
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_title('Interactive legend', size=20)
        
        mpld3.show()
        

        https://mpld3.github.io/quickstart.html

        【讨论】:

          猜你喜欢
          • 2011-06-27
          • 1970-01-01
          • 2015-12-18
          • 2015-06-12
          • 2019-10-24
          • 2020-08-03
          • 2017-10-18
          • 2011-11-15
          • 2011-02-03
          相关资源
          最近更新 更多