kms
kms

Reputation: 2024

Conditional color style : plotly go.Bar

I'd like add conditional styling to a plotly stacked bar plot. Specifically, the top bar of the stack would be conditional based on the x-axis values.

Here's my code:

# sample df
df = pd.DataFrame({'Date': ['2010 - Q3','2010 - Q4','2011 - Q1','2011 - Q2','2011 - Q3','2011 - Q4'],
                   'Rate' : ['11.4','12.2','14.4','15.5','10.1','13.1'],
                   'Rate1': ['2.1','2.3','1.9','1.6','2.5','1.1']
                 })


clrs = 'rgb(222,0,0)'


fig = go.Figure(

            data=[

                  go.Bar(
                        x=df['Date'],
                        y=df['Rate'],
                        name='Natural Level'
                        ),

                  go.Bar(
                        x=df['Date'],
                        y=df['Rate1']),
                        name='Change',
                        marker=dict(color=clrs)
                        )

                  ],

            layout=go.Layout(

                title='Measuring excess demand and supply in the market.',

                xaxis=dict(
                    tickangle=90,
                    tickfont=dict(family='Rockwell', color='crimson', size=14)
                ),

                yaxis=dict(
                    title='Rate',
                    showticklabels=True
                ),

                barmode='stack',

            )
        ) 

The clrs variable takes the color value conditional on the list of x axis values. i.e clrs = rgb(222,0,0) if df['Date'] in lst else rgb(0,222,0).

where lst is list of x-axis values.

enter image description here

Upvotes: 3

Views: 5432

Answers (2)

Derek O
Derek O

Reputation: 19610

Original method: you can create a Color column in your df based on your condition, then pass this column to the color parameter in marker=dict(color=clrs).

EDIT: you can slice the dataframe based on whether the Date column is in lst, then add both parts of the dataframe separately uses traces, specifying the color for each trace. This isn't the prettiest solution and should be replaced by a loop if you have more than two colors, but hopefully gets the job done here.

import pandas as pd
import plotly.graph_objects as go

## sample df
df = pd.DataFrame({'Date': ['2010 - Q3','2010 - Q4','2011 - Q1','2011 - Q2','2011 - Q3','2011 - Q4'],
                   'Rate' : ['11.4','12.2','14.4','15.5','10.1','13.1'],
                   'Rate1': ['2.1','2.3','1.9','1.6','2.5','1.1']
                 })

## first and last bar are in lst
lst = ['2010 - Q3', '2011 - Q4']

## NOT NEEDED ##

## add a color column to the df, apply along row
## df['Color'] = df.apply(lambda x: 'rgb(222,0,0)' if x['Date'] in lst else 'rgb(0,222,0)', axis=1)
## clrs = 'rgb(222,0,0)'

fig = go.Figure(

            data=[

                  go.Bar(
                        x=df['Date'],
                        y=df['Rate'],
                        name='Natural Level'
                        ),

                  ],

            layout=go.Layout(

                title='Measuring excess demand and supply in the market.',

                xaxis=dict(
                    tickangle=90,
                    tickfont=dict(family='Rockwell', color='crimson', size=14)
                ),

                yaxis=dict(
                    title='Rate',
                    showticklabels=True
                ),

                barmode='stack',

            )
        ) 

## part of the dataframe in the lst
fig.add_trace(go.Bar(
                        x=df[df['Date'].isin(lst)]['Date'],
                        y=df[df['Date'].isin(lst)]['Rate1'],
                        name='Change1',
                        marker=dict(color='rgb(222,0,0)')
                        )

    )
fig.add_trace(go.Bar(
                        x=df[~df['Date'].isin(lst)]['Date'],
                        y=df[~df['Date'].isin(lst)]['Rate1'],
                        name='Change2',
                        marker=dict(color='rgb(0,222,0)')
                        )

    )

fig.show()

enter image description here

Upvotes: 5

r-beginners
r-beginners

Reputation: 35230

The basic form is how to create a list of colors for the x-axis, so there are many different approaches. I suggest this as an example of how to make a color list with conditions.

import pandas as pd
import plotly.graph_objects as go

# sample df
df = pd.DataFrame({'Date': ['2010 - Q3','2010 - Q4','2011 - Q1','2011 - Q2','2011 - Q3','2011 - Q4'],
                   'Rate' : ['11.4','12.2','14.4','15.5','10.1','13.1'],
                   'Rate1': ['2.1','2.3','1.9','1.6','2.5','1.1']
                 })

clrs = []
for i in range(len(df)):
    if df.loc[i,'Date'][:4] == '2010':
        clrs.append('rgb(222,0,0)')
    else:
        clrs.append('rgb(0,100,0)')
#clrs = ['rgb(222,0,0)','rgb(222,0,0)','rgb(0,100,0)','rgb(0,100,0)','rgb(0,100,0)','rgb(0,100,0)']


fig = go.Figure(
            data=[
                  go.Bar(
                        x=df['Date'],
                        y=df['Rate'],
                        name='Natural Level'
                        ),
                  go.Bar(
                        x=df['Date'],
                        y=df['Rate1'],
                        name='Change',
                        marker=dict(color=clrs)
                        )
                  ],
            layout=go.Layout(
                title='Measuring excess demand and supply in the market.',
                xaxis=dict(
                    tickangle=90,
                    tickfont=dict(family='Rockwell', color='crimson', size=14)
                ),
                yaxis=dict(
                    title='Rate',
                    showticklabels=True
                ),
                barmode='stack',
            )
        )

fig.show()

enter image description here

Upvotes: 3

Related Questions