简体   繁体   中英

Plotly replace x label with image

I have a graph in plotly which I want to replace the x labels. 在此处输入图片说明

I pasted this graph as an example. At the bottom you will see ARI, ATL, BAL, etc. I was wondering if its possible to replace these with images? Icons?

  • same approach that @r-begginers provided in referenced answer
  • have sourced all logos from kaggle . Used PIL for encoding
  • have synthesized as an axis by creating a second trace with a -ve percentage and used that plot area to place logos
  • have set xaxis to invisible so hover provided the team abbreviation

import kaggle.cli
import sys, requests
import pandas as pd
from pathlib import Path
from zipfile import ZipFile
import urllib
import plotly.express as px
from PIL import Image

# fmt: off
# download data set
url = "https://www.kaggle.com/anzhemeng/nfl-team-logos"
sys.argv = [sys.argv[0]] + f"datasets download {urllib.parse.urlparse(url).path[1:]}".split(" ")
kaggle.cli.main()
zfile = ZipFile(f'{urllib.parse.urlparse(url).path.split("/")[-1]}.zip')
# fmt: on
zfile.extractall("nfl-logos")
df = pd.DataFrame(Path.cwd().joinpath("nfl-logos").glob("*.png"), columns=["filename"])
df["team"] = df["filename"].apply(lambda d: d.stem)
df["passResult"] = np.random.uniform(0, 1, len(df))
df = df.sort_values("team")

fig = px.scatter(df, x="team", y="passResult").add_traces(
    px.scatter(df, "team", np.full(len(df), -0.05))
    .update_traces(marker_color="rgba(0,0,0,0)", hovertemplate="%{x}")
    .data
)

for x in fig.data[0].x:
    fig.add_layout_image(
        source=Image.open(df.loc[df["team"].eq(x), "filename"].values[0]),
        x=x,
        y=-0.01,
        xref="x",
        yref="y",
        xanchor="center",
        sizex=1,
        sizey=1,
    )

fig.update_layout(xaxis={"visible":False})

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM