python plotly treemap: Add images to labels

Viewed 66

I am trying to add logos to the labels in a treemap in Python Plotly express.

I would like to replace text labels with logo PNG images.

I would like the pictures to fit to the relative areas. Also for the treemap to be interactive.
So the images will resize and move relative to the area. Hence I am trying to add them to the labels and not overlaying them on to the figure.

Below is the minimal reproducible code.
In the origin code the treemap has more attributes, the images are different for each skill and images stored locally.

from urllib.request import urlopen
from PIL import Image
import pandas as pd 
import plotly.express as px

# Get sample image for site
img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1200px-Python-logo-notext.svg.png"
img = Image.open(urlopen(img_url))

# Create data frame 
data = {'skills' : ['c#', 'pyhton', 'r', 'sas', 'sql'],
        'count' : [0, 19, 14, 7, 40],}

df = pd.DataFrame(data)
df['groups'] = 'Languages'
df['images'] = img 

# Create treemap 
fig = px.treemap(df, path=[px.Constant("all"),'groups','skills'], values='count', labels= "images",)

fig.update_traces(root_color="lightgrey")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))

# Update labels to images
fig.update_traces(labels = df["images"], selector=dict(type='treemap'))

fig.show()

Can anyone show me where I am going wrong please?

0 Answers
Related