plotly / plotly.py

The interactive graphing library for Python :sparkles: This project now includes Plotly Express!
https://plotly.com/python/
MIT License
16.22k stars 2.55k forks source link

filled contour plot in plotly.express #2071

Closed lucanics closed 4 years ago

lucanics commented 4 years ago

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! :)

emmanuelle commented 4 years ago

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

lucanics commented 4 years ago

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..

nicolaskruchten commented 4 years ago

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

image

lucanics commented 4 years ago

Many thanks, that solves all my problems

nicolaskruchten commented 4 years ago

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

lucanics commented 4 years ago

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()