matplotlib with mpld3 to plot in html page

  1. matplotlib import and config

    import matplotlib
    matplotlib.use(‘Agg’)
    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    import mpld3

    plt.style.use(‘bmh’)

    1. load some configuration

    s = json.load(open(f”{{script_root}\plot_config.json”))
    matplotlib.rcParams.update(s)
    fig = plt.figure()
    ax = fig.add_subplot(111) # 1×1 grid,

    “right side shift or padding”
    fig.subplots_adjust(right=sub_plot_adj)

    # set plot color profile
    ax.set_prop_cycle(color=chart_colors)

    plot_config.json

      {
        "font.size": 13,
        "lines.linewidth": 2.0,
         "figure.figsize": [17,8],
         "axes.labelsize": "medium"
      }
    

    — more see matplotlib website

  2. plot

    ax.plot(x_axis_data’, y_axis_data, label=legend_item)

    ax.set_title(‘demo’, size=16)
    ax.set_xlabel(‘x data’)
    ax.xaxis.set_label_coords(0.95, -0.08)
    ax.set_ylabel(‘(y_data)’))
    ax.yaxis.set_label_coords(-0.035, 0.96)

    “connect legend”
    handles, labels = ax.get_legend_handles_labels()
    interactive_legend = mpld3.plugins.InteractiveLegendPlugin(handles,

                                                            labels, alpha_unsel=0.0,
                                                            alpha_over=1.5,
                                                            font_size=12,
                                                            start_visible=True)

    mpld3.plugins.connect(fig, interactive_legend)

    “jsonlize the data”

    graph_json_data = json.dumps(mpld3.fig_to_dict(fig))

    “garbage collection”
    fig.clf()
    plt.close()

    then return this graph_json_data for html page.

    # set x and y axis lim
    plt.xlim(2, 10)
    plt.ylim(5, 15)

  3. Html page

    “also need add mpld3 plugins js from mpld3 plugin class”

matplotlib is a great library