Search code examples
pythonplotlyvisualizationpie-chartplotly-python

Changing the opacity of individual slices of a Plotly pie-chart


I am building some interactive data-charts with plotly express & dash. I already have some features like clicking on a piece to pull it from the pie-chart.

For improved highlighting, I wanted to adjust the opacity of the pulled piece.

The documentation states that you can pass a parameter for the keyword opacity between 0 and 1 in the function update_traces()..

fig.update_traces(opacity=0.5)

However, this affects the whole chart. I was wondering if it is possible to set the opacity for each slice individually (like with fig.update_traces(pull=) where you can pass a list for the pull of each slice)


Solution

  • Since transparency only accepts float values, the CSS color name is specified in this reference example, but this can be handled by specifying transparency for each individual color with rgba(255,0,0,0.5), for example.

    import plotly.graph_objects as go
    
    #colors = ['gold', 'mediumturquoise', 'darkorange', 'lightgreen']
    colors = ['rgba(255,215,0,0.5)', 'rgba(72,209,204,0.75)', 'rgba(255,140,0,0.65)', 'rgba(144,238,144,0.9)']
    
    fig = go.Figure(data=[go.Pie(labels=['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen'],
                                 values=[4500,2500,1053,500])])
    fig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20,
                      marker=dict(colors=colors, line=dict(color='#000000', width=2)))
    fig.show()
    

    enter image description here

    example of reference enter image description here