Home > Back-end >  Color coding Tree map with PLOTLY
Color coding Tree map with PLOTLY

Time:06-03

My requirement is to plot a Tree map using python and I am using plotly for the same... The Data frame which is close to my real time data is as follows

import pandas as pd
import plotly.express as px

data_frame = pd.DataFrame({'region':['AA','AB','AC','AD','AE'],
                           'number':[2,12,6,11,30],
                           'percentage':[94.03,91.23,95.66,97.99,99.22]})

And the plot from the following code, looks something like this

fig = px.treemap(data_frame, path= [data_frame['region']],
                 values=data_frame['number'],color=data_frame['percentage'])

fig.show()

The PLOT

enter image description here

BUT, i would like to have the color coding based on the column "percentage" with the custom scale as follows

  • data_frame['percentage'] > 98 : green (#00ff00)
  • data_frame['percentage'] between 95 - 98 : amber (#ffbf00)
  • data_frame['percentage'] < 95 red (#ff0000)

To be clear, I would only need the 3 colors mentioned above in my graph. These colors should be assigned based on the percentage values. How can i achieve this?

CodePudding user response:

I think you have to add new columns to facilitate color matching. Please refer below code:

import pandas as pd
import plotly.express as px
import numpy as np

data_frame = pd.DataFrame({'region':['AA','AB','AC','AD','AE'],
                           'number':[2,12,6,11,30],
                           'percentage':[94.03,91.23,95.66,97.99,99.22]})


condition = [data_frame['percentage']>98,
            (data_frame['percentage']>95)&(data_frame['percentage']<98),
            data_frame['percentage']<95]

choices = ['A','B','C']
data_frame['Condition'] = np.select(condition,choices,default='D')

fig = px.treemap(data_frame, path= [data_frame['region']],
                 values=data_frame['number'],color=data_frame['Condition'],
                 color_discrete_map={'A':'#00ff00',
                                     'B':'#ffbf00',
                                     'C':'#ff0000',
                                     'D':'#AB63FA'})

fig.show()

So graph will be showed like below: enter image description here

  • Related