[PYTHON] Run pandas-highcharts display_charts in an environment other than jupyter

background

It seems that people who do data analysis often use jupyter. Perhaps Python alone is not good at drawing data as a graph immediately, so I think that it is done on the browser. However, display (html drawing) related methods such as display are unique to jupyter and cannot be executed in other environments. Even if you refer to the data analysis article of Qiita, if it is an article of jupyter environment, it may not work if the drawing surroundings are your own environment. This time, I wrote an article because I needed to see the graph displayed by pandas-highcharts from the pycharm environment.

Method

I made the following function by referring to the source code of pandas-highcharts. Since display_charts of pandas-highcharts has been set to display by return, the return value will be None. Just before that, it feels like it is embedded in the html template and returned. (reference) https://github.com/gtnx/pandas-highcharts/blob/master/pandas_highcharts/display.py

def my_display_charts(df, chart_type="default", render_to=None, **kwargs):
    from pandas_highcharts.core import serialize
    from pandas_highcharts.display import _generate_div_id_chart
    if chart_type not in ("default", "stock"):
        raise ValueError("Wrong chart_type: accept 'default' or 'stock'.")
    chart_id = render_to if render_to is not None else _generate_div_id_chart()
    json_data = serialize(df, render_to=chart_id, chart_type=chart_type, **kwargs)

    content = """
    <div id="{chart_id}"</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/8.1.1/highstock.min.js"></script>
    <script type="text/javascript">{data}</script>
    """

    html = """
    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <title>My Result</title>
    </head>
    <body>
        {content}
    </body>
    </html>
    """
    return html.format(content=content.format(chart_id=chart_id, data=json_data))

The usage is like this.

import pandas as pd
import webbrowser
import os

def my_display_charts(df, chart_type="default", render_to=None, **kwargs):
    from pandas_highcharts.core import serialize
    from pandas_highcharts.display import _generate_div_id_chart
    if chart_type not in ("default", "stock"):
        raise ValueError("Wrong chart_type: accept 'default' or 'stock'.")
    chart_id = render_to if render_to is not None else _generate_div_id_chart()
    json_data = serialize(df, render_to=chart_id, chart_type=chart_type, **kwargs)

    content = """
    <div id="{chart_id}"</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/8.1.1/highstock.min.js"></script>
    <script type="text/javascript">{data}</script>
    """

    html = """
    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <title>My Result</title>
    </head>
    <body>
        {content}
    </body>
    </html>
    """
    return html.format(content=content.format(chart_id=chart_id, data=json_data))

df = pd.DataFrame([1, 2, 3, 5, 4], index=[list('abcde')])
html_data = my_display_charts(df, chart_type="stock", title="Mt Result", figsize=(640, 480), grid=True)
path = 'index.html'

with open(path, mode='w') as f:
    f.write(html_data)

webbrowser.open_new_tab('file:///' + os.getcwd() + '/' + path_w)

Hopefully it will draw like this in your PC's default browser. It's annoying that the browser opens every time, but I can see it for the time being. The graph is awkward because it is a properly generated Dataframe.

コメント 2020-06-10 204410.png

Consideration

Why is the horizontal axis the time stamp by default? It is best if you can pass the html element as a character string to the webbrowser, but it seems that there is only a way to pass the path, so this time I wrote it as index.html once. In the same way, IPython.display, python-higchart, etc. can be displayed in the browser as long as the html element can be extracted. This time I only had to load highstock.min.js, but in some cases highchart.js may also be needed. As for highstock.min.js, I didn't know where the formula was, so I brought it from the following. https://cdnjs.com/libraries/highcharts

Click here for the official page https://www.highcharts.com/

Recommended Posts

Run pandas-highcharts display_charts in an environment other than jupyter
Run eclipse in Docker environment (noVNC)
Created an environment for Anaconda & Jupyter
Learn machine learning anytime, anywhere in an on-demand Jupyter Notebook environment
Use tensorflow in an environment without root
Create and run embulk config in Jupyter
Creating a virtual environment in an Anaconda environment
Install the package in an offline environment
Send an email with a user other than EMAIL_HOST_USER written in settings in django
Run PIFuHD in Windows + Anaconda + Git Bash environment
Building an environment that uses Python in Eclipse
Browser specification of Jupyter Notebook in Windows environment
Install the python package in an offline environment
Error running Jupyter Notebook in Anaconda virtual environment
Install LightGBM in an OS X virtualenv environment