Learn how to use Dash Bio for next-gen sequencing & quality control. 🧬 Register for the Oct 27 webinar.

Conversion of matplotlib contour plots to plotly contour plots

Actually I am trying to plot Hyperbola in plotly. For that I first converted matplotlib hyperbola plot to plotly plot. And I faced a UserWarning from plotly.

This is my matplotlib code,

x = np.linspace(-10, 10, 400)
y = np.linspace(-5, 5, 400)
x, y = np.meshgrid(x, y)

range_ = [-6.0, -5.0]
a = range_[0]
b = range_[1]

plt.figure(figsize=(10, 5))
plt.contour((x**2/a**2 - y**2/b**2), [1], colors='g')
plt.show()

This gave me nice Hyperbola plot. Hence I wanted to make the same plot in plotly.

Here is my plotly version of the same code.

hyper = plt.gcf() # this is an object of matplotlib plot.

plot_hyper = tls.mpl_to_plotly(hyper)

layout = go.Layout(
    title='Hyperbola',
    font=dict(family='IBM Plex Mono, monospace', color='black'),
    plot_bgcolor='#fafafa',
    paper_bgcolor='#fafafa',
    width=800,
    xaxis=dict(
        zeroline=False,
        tickfont=dict(
            family='Crimson Text, serif',
            size=15,
            color='black'
        ),
    ),
    yaxis=dict(
        zeroline=False,
        tickfont=dict(
            family='Crimson Text, serif',
            size=15,
            color='black'
        ),
    )
)

plot_hyper['layout'] = layout
py.iplot(plot_hyper)

This gives me an empty plot. Please guide me to attain this. Thanks in advance.

Hi @acesaif,

I’d recommend building the figure with the plotly contour trace type directly (https://plot.ly/python/contour-plots/). Here’s an example that i think it pretty close to the matplotlib version

import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()

x = np.linspace(-10, 10, 400)
y = np.linspace(-5, 5, 400)
x, y = np.meshgrid(x, y)

a = 1
b = 2
z = x**2/a**2 - y**2/b**2

contour = go.Contour(
    z=z
)

contour.contours.type = 'constraint'
contour.contours.value = 1
data = [contour]

fig = go.Figure(data=data)
iplot(fig)

Hope that helps!
-Jon

1 Like

Thank you so much @jmmease. That is very helpful.

1 Like