Plotly.py: filled contour plot in plotly.express

Created on 15 Jan 2020  路  6Comments  路  Source: plotly/plotly.py

Is there a way to create filled contour plots with plotly.express similar to the following one?
contour2
(reference: https://plot.ly/python/contour-plots/)

The only ones I have seen so far with plotly.express are not filled, e.g.:

import plotly.express as px
df = px.data.iris()
fig = px.density_contour(df, x="sepal_width", y="sepal_length", color="species", marginal_x="rug", marginal_y="histogram")
fig.show()

contour1
(reference: https://plot.ly/python/plotly-express/)

Any help is appreciated! :)

Most helpful comment

You can set the colorscale in the update_traces() call like this:

image

All 6 comments

Hi, after a print(fig) to understand the structure of the figure created by plotly express, you can call fig.update_traces to change the configuration of the trace. See the example below

import plotly.express as px
df = px.data.iris().query("species == 'virginica'")
fig = px.density_contour(df, x="sepal_width", y="sepal_length")
fig.update_traces(contours_coloring='fill')
fig.show()

image

That's perfect, thanks! And how can you change the colorscale?

I have found this reference: https://plot.ly/python/contour-plots/ which uses graph objects to change the colorscale:

fig = go.Figure(go.Histogram2dContour(
        x = x,
        y = y,
        colorscale = 'Blues'
))

but I am unable to do the equivalent in plotly.express..

You can set the colorscale in the update_traces() call like this:

image

Many thanks, that solves all my problems

@Mahdis-z can you add these examples or similar to https://plot.ly/python/2d-histogram-contour/ please?

In case this is useful to anyone, I needed this kind of plot in combination with animation frames.

Although the solution below might not be very beautiful using the iris dataset, you might have a better usecase for other dataframes:

import plotly.express as px
df = px.data.iris()
df_w = df["sepal_width"].copy()
df_l = df["sepal_length"].copy()

fig = px.density_contour(df, x="sepal_width", y="sepal_length", 
                         range_x=[df_w.min(),df_w.max()], 
                         range_y = [df_l.min(), df_l.max()],
                         animation_frame="species")

fig.data[0]["contours"].coloring = "fill"
fig.update_traces(colorscale="Viridis")

for num,frames in enumerate(fig.frames, start=0):
    fig.frames[num].data[0]["contours"].coloring = "fill"

fig.show()
Was this page helpful?
0 / 5 - 0 ratings

Related issues

dhirschfeld picture dhirschfeld  路  4Comments

tssweeney picture tssweeney  路  4Comments

suciokhan picture suciokhan  路  3Comments

EmilienDupont picture EmilienDupont  路  4Comments

jisaacso picture jisaacso  路  4Comments