pythonplotlyplotly-python

Plotly: How to specify colors for a group using go.Bar?


How to use plotly.graph_objs to plot pandas data in a similar way to plotly.express - specifically to color various data types?

The plotly express functionality to group data types based on a value in a pandas column is really useful. Unfortunately I can't use express in my system (as I need to send the graph object to orca)

I'm able to get the same functionality by specifically mapping Type to colours (full_plot in the example below), however I have types A-Z, is there a better way of mapping each possible Type in the dataframe to a color?

import pandas as pd
import plotly.express as px
import plotly.graph_objs as go

d = {'Scenario': [1, 2, 3, 1, 2,3],
     'Type': ["A", "A", "A", "B", "B", "B"],
     'VAL_1': [100, 200, 300, 400 , 500, 600],
     'VAL_2': [1000, 2000, 3000, 4000, 5000, 6000]}
df = pd.DataFrame(data=d)


def quick_plot(df):

    fig = px.bar(df, y='VAL_1',  x='Scenario',  color="Type", barmode='group')
    fig['layout'].update(title = "PX Plot",
                     width = 600, height = 400,
                     xaxis = dict(showgrid=False))
    fig.show()


def full_plot(df):

    colors = {'A': 'blue',
          'B': 'red'}
    s0=df.query('Type=="A"')
    s1=df.query('Type=="B"')

    fig = go.Figure()
    fig.add_trace(go.Bar(
        name='A',
         y=s0['VAL_1'],x=s0['Scenario'], marker={'color': colors['A']}))
    fig.add_trace(go.Bar(
        name='B',
         y=s1['VAL_1'],x=s1['Scenario'], marker={'color': colors['B']}))

    fig['layout'].update(title = "Full Plot",
                     width = 600, height = 400)

    fig.update_layout(barmode='group')
    fig.show()

quick_plot(df)
full_plot(df)

Solution

  • You could simply use a dictionary like this:

    colors = {'A':'steelblue',
              'B':'firebrick'}
    

    The only challenge lies in grouping the dataframe for each unique type and adding a new trace for each type using a for loop. The code snippet below takes care of that to produce this plot:

    enter image description here

    # imports
    import pandas as pd
    import plotly.express as px
    import plotly.graph_objs as go
    
    # data
    d = {'Scenario': [1, 2, 3, 1, 2,3],
         'Type': ["A", "A", "A", "B", "B", "B"],
         'VAL_1': [100, 200, 300, 400 , 500, 600],
         'VAL_2': [1000, 2000, 3000, 4000, 5000, 6000]}
    df = pd.DataFrame(data=d)
    
    # assign colors to type using a dictionary
    colors = {'A':'steelblue',
              'B':'firebrick'}
    
    # plotly figure
    fig=go.Figure()
    for t in df['Type'].unique():
        dfp = df[df['Type']==t]
        fig.add_traces(go.Bar(x=dfp['Scenario'], y = dfp['VAL_1'], name=t,
                             marker_color=colors[t]))
    
    fig.show()