Plotly hover to show multiple values in pie chart

Viewed 671

I am trying to create a pie chart using a dataframe that shows breakdown data on hover.

The dataframe I am using is similar to the below:

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

d = {'Customer': ['Cust 1', 'Cust 1', 'Cust 2', 'Cust 1', 'Cust 2', 'Cust 2', 'Cust 3', 'Cust 3','Cust 4', 'Cust 4', 'Cust 5', 'Cust 4','Cust 5', 'Cust 6', 'Cust 6', 'Cust 6'], 
         'Product': ['DIGITAL', 'DIGITAL', 'STORE', 'DIGITAL', 'DIGITAL', 'STORE', 'DIGITAL', 'DIGITAL', 'DIGITAL', 'DIGITAL', 'STORE', 'DIGITAL', 'STORE', 'DIGITAL', 'DIGITAL', 'STORE'], 
         'PO': ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9', 'P10', 'P11', 'P12', 'P13', 'P14', 'P15', 'P16'],
         'Revenue': [100, 120, 240, 200, 110, 100, 120, 180, 100, 120, 240, 200, 110, 100, 120, 180]}
    
df = pd.DataFrame(data=d)

Output:

fig = px.pie(d, values='Revenue', names='Product')
fig.show()

This produces a pie chart AOK, but what I am wanting to do is, on hover, show a breakdown of each customer and their Revenue for the Product.

So each hover would have a list of each customer that bought the product, and their total revenue. For example if you hovered over Digital, the hover box would show:

Digital
Cust 1: 420
Cust 2: 110
Cust 3: 300
Cust 4: 420
Cust 6: 220

Any help will be appreciated. Im new to Plotly, so not exactly sure how to ask the question, let me know if you need more clarity.

1 Answers

Currently, you can't split pie charts in plotly. An alternative is the sunburst chart. This can show hierarchical data, which fits in this situation where there are multiple customers for each product. Here is an example with the provided data:

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

d = {'Customer': ['Cust 1', 'Cust 1', 'Cust 2', 'Cust 1', 'Cust 2', 'Cust 2', 'Cust 3', 'Cust 3','Cust 4', 'Cust 4', 'Cust 5', 'Cust 4','Cust 5', 'Cust 6', 'Cust 6', 'Cust 6'], 
         'Product': ['DIGITAL', 'DIGITAL', 'STORE', 'DIGITAL', 'DIGITAL', 'STORE', 'DIGITAL', 'DIGITAL', 'DIGITAL', 'DIGITAL', 'STORE', 'DIGITAL', 'STORE', 'DIGITAL', 'DIGITAL', 'STORE'], 
         'PO': ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9', 'P10', 'P11', 'P12', 'P13', 'P14', 'P15', 'P16'],
         'Revenue': [100, 120, 240, 200, 110, 100, 120, 180, 100, 120, 240, 200, 110, 100, 120, 180]}
    
df = pd.DataFrame(data=d)

fig = px.sunburst(df, values='Revenue', path=['Product','Customer'])
fig.show()

Output: enter image description here

Related