Customize barplot colors by combining Hvplot ('Plotly extension') + Panel Widgets

Viewed 42

I'm trying to explain the title with an example:

I have a dataframe like this:

enter image description here

Now, my task is plotting in a way like this: enter image description here

The picture above is made using plotly express only. However, my task is to make it interactive by adding panel widgets like these ones:

enter image description here

So, now I showed all objects, I report my code so far:

from pydataset import data as pyds
import panel as pn
pn.extension()
import hvplot.pandas
import plotly.express as px
import pandas as pd

df=pyds('HairEyeColor')
df_sex=df.groupby(['Sex','Hair','Eye'],sort=False).sum().reset_index()

px.bar(df,y='Freq',x='Sex',facet_col='Hair',color='Eye',barmode='group',
    color_discrete_map={'Brown':'Brown','Blue':'Blue','Hazel':'Coral','Green':'Green'})

Sex=pn.widgets.CheckButtonGroup(name='Gender',options=['Male','Female'],button_type='warning')
Freq=pn.widgets.IntSlider(name='Freq',start=min(df.Freq),end=max(df.Freq),step=2,value=min(df.Freq))
Hair=pn.widgets.CheckButtonGroup(name='Hair',options=['Black','Brown','Red','Blond'],value= ['Black'],button_type='success')
Eye=pn.widgets.CheckButtonGroup(name='Eye',options=['Brown','Blue','Hazel','Green'],value=['Brown'],button_type='primary')

hv.extension('plotly')
idf_sex=df_sex.interactive()
pipe=idf_sex[(idf_sex.Sex.isin(Sex)) & (idf_sex.Freq>=Freq) & (idf_sex.Hair.isin(Hair) & (idf_sex.Eye.isin(Eye)))]

pipe.hvplot(kind='bar',y='Freq',x='Sex',by='Hair', c='Eye',stacked=False)

Which gives me this:

enter image description here

As u can see, there's a problem: I want it to display 4 colors according to 'Eye' colors. So, I'm trying to implement a panel interaction with a function like this:

color_discrete_map={'Brown':'Brown','Blue':'Blue','Hazel':'Coral','Green':'Green'}
@pn.depends(Eye)
def coloriamo(x=Eye.value):
    global out
    for i,j in color_discrete_map.items():
        if x==color_discrete_map[i]:
            out=x
        return out
pipe.hvplot(kind='bar',y='Freq',x='Sex',by='Hair', c=pn.bind(coloriamo,Eye),stacked=False)

Unfortunatly, it doesn't work and I get the message:

NameError: name 'out' is not defined

It's clear that I don't even know how to set my 'coloriamo' function work. Please, have you an idea how to make it work? Thanks

0 Answers
Related