pythonplotlyplotly-python

How to create discrete colormap with n colors using Plotly


I would like to create a colormap with n colors for a plotly express plot in Python, which should fade from one color into another. All the default colormaps only have 10 discrete values, but I am looking for a colormap with n > 10 discrete values.

>>> px.colors.sequential.Plasma_r

['#f0f921',
 '#fdca26',
 '#fb9f3a',
 '#ed7953',
 '#d8576b',
 '#bd3786',
 '#9c179e',
 '#7201a8',
 '#46039f',
 '#0d0887']

Is there a way to split a continuous map into n parts?


Solution

  • If you don't mind rgb colors, then n_colors is one way to go. Here's an example of 15 colors in a gray scale between 'rgb(0, 0, 0)' and 'rgb(255, 255, 255)':

     n_colors('rgb(0, 0, 0)', 'rgb(255, 255, 255)', 15, colortype='rgb')
    

    enter image description here

    And here's an example of 25 colors between blue 'rgb(0, 0, 255)'and red , 'rgb(255, 0, 0)' :

    n_colors('rgb(0, 0, 255)', 'rgb(255, 0, 0)', 25, colortype = 'rgb')
    

    enter image description here

    Complete code:

    import numpy as np
    import pandas as pd
    import plotly.graph_objects as go
    import plotly.express as px
    import datetime
    from plotly.colors import n_colors
    
    pd.set_option('display.max_rows', None)
    pd.options.plotting.backend = "plotly"
    
    
    # greys15 = n_colors('rgb(0, 0, 0)', 'rgb(255, 255, 255)', 15, colortype='rgb')
    redVSblue = n_colors('rgb(0, 0, 255)', 'rgb(255, 0, 0)', 25, colortype = 'rgb')
    
    fig = go.Figure()
    
    # for i, c in enumerate(greys15):
    for i, c in enumerate(redVSblue):
        fig.add_bar(x=[i], y = [i+1], marker_color = c, showlegend = False)
    f = fig.full_figure_for_development(warn=False)
    fig.show()