✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Showing matplotlib figures with Dash (mpl_to_plotly)

Hello,

I am new to Dash, and I would like to use it to publish my existing code online. Within a code I have a lot of matplotlib figures, so I am looking for the most convenient way to upload them. I think the easiest way is to use mpl_to_plotly. However, I am not successful in getting the output. I have tried producing a minimal example - just a simple Dash app that is going to post a simple matplotlib figure. I am attaching the code below:

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import json
import pandas as pd
import numpy as np
import plotly
import os
import csv
import plotly.tools as tls
import plotly.graph_objs

import matplotlib.pyplot as plt

app = dash.Dash()

app.scripts.config.serve_locally = True

app.css.config.serve_locally = True

app.layout = html.Div([
html.Div(id=‘graphs’,children=dcc.Graph(id=‘dummy’)),
])

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4], [10, 20, 25, 30], color=‘lightblue’, linewidth=3)
ax.scatter([0.3, 3.8, 1.2, 2.5], [11, 25, 9, 26], color=‘darkgreen’, marker=’^’)
ax.set_xlim(0.5, 4.5)

fig_url=tls.mpl_to_plotly(fig)

dcc.Graph(id=‘graphs’, figure=fig_url)

app.css.append_css({
‘external_url’: ‘https://codepen.io/chriddyp/pen/bWLwgP.css
})

if name == ‘main’:
app.run_server(debug=True)

However, this code just produces a blank figure as below. Do you have idea on what could be wrong?

See the complete example, if helpful anyway:

from plotly.tools import mpl_to_plotly
from matplotlib import pyplot as plt
import dash
import dash_html_components as html
import dash_core_components as dcc

app= dash.Dash()

fig= plt.figure()
ax= fig.add_subplot(111)
ax.plot(range(10), [i**2 for i in range(10)])
ax.grid(True)
plotly_fig = mpl_to_plotly(fig)

app.layout= html.Div([
    dcc.Graph(id= 'matplotlib-graph', figure=plotly_fig)

])

app.run_server(debug=True, port=8010, host='localhost')

1 Like

Just a heads up: mpl_to_plotly no longer works with the current version of matplotlib, and is considered to be deprecated.

1 Like