Search code examples
pythonplotlyplotly-python

How to change Plotly express scatterplot continuous colormap?


I was plotting a scatterplot in plotly express as the attached pics. Here the size of points are based on the number of occurrence (more occurrence= larger size of point) enter image description here

But I am unable to change the colormap of the figure. I tried using the continuous colormap keyword for scatter plot as well as generate colormap in matplotlib and then use it in plotly and both didnt work.

I am looking for a continuous colormap consists of yellow (low value) blue (mid range values) and red (high range values).

My current code is as follows:

import pandas as pd
import matplotlib.colors
A= pd.read_csv('example.csv')
dA= A['ML']
dB= A['Radio']
dC= A['Occur']

norm=plt.Normalize(-1,1)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", 
["yellow","mediumblue","orangered"])

import plotly.express as px

fig = px.scatter(A, x="ML", y="Radio", color="Occur",color_discrete_sequence= 
["red", "blue", "yellow"]
             ,size='Occur')
fig.update_layout(
font_family="Times New Roman",
legend_title_font_color="green" ,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
xaxis = dict(
    tickmode = 'linear',color= '#000000',
    tick0 = 0,
    dtick = 15
),
yaxis = dict(
    tickmode = 'linear',color= '#000000',
    tick0 = 0,
    dtick = 1
),
font=dict(
    family="Times New Roman",
    size=18,
    color='#000000'
)
)
fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=True)
fig.update_yaxes(showline=True, linewidth=1, linecolor='black', mirror=True)

Solution

  • The continuous colormap specification is 'color_continuous_scale'. If any color is specified here, it will be processed on the plotly side. If the color range is set arbitrarily, a tuple of the range value and color is specified. For data and code, please refer to the official reference.

    import plotly.express as px
    df = px.data.iris()
    
    fig = px.scatter(df,
                     x="sepal_width",
                     y="sepal_length",
                     color='petal_length',
                     color_continuous_scale=[(0,'yellow'), (0.5, 'blue'), (1,'red')],
                     template='plotly_white'
                    )
    
    fig.show()
    

    enter image description here