I'm trying to make a graph where the dots of a scatterplot are chess pieces. For now the code is very simple:
fig = px.scatter(
x = df_game.x,
y = df_game.y,
color = df_game.color,
symbol = df_game.icon,
opacity = 0.1
)
fig.show()
But I want something like this one:
My dataframe contains the (x, y) position for every piece on every turn, like this:
turn piece color x y icon
0 0 r w 1 1 icons/wr.svg
1 0 n w 1 2 icons/wn.svg
2 0 b w 1 3 icons/wb.svg
3 0 q w 1 4 icons/wq.svg
4 0 k w 1 5 icons/wk.svg
and the icons that I want to use are in the column icon
.
How can I change the default icons to my .svgs?
I was able to convert an SVG image to a PNG image and display it. The library to be installed is 'cariosvg'. Use it to convert the converted binary to a string in base64 and set it as the reference for the image.
import plotly.express as px
import base64
import cairosvg
import io
x = df['x'].tolist()
y = df['y'].tolist()
chess_images = df['icon'].tolist()
fig = px.scatter(x=x, y=y)
for i,(src,yy) in enumerate(zip(chess_images, y),start=1):
img = io.BytesIO(cairosvg.svg2png(url='./data/chess/'+src))
base_img = base64.b64encode(img.read())
fig.add_layout_image(
source='data:image/png;base64,{}'.format(base_img.decode()),
xref="x",
yref="y",
x=i,
y=yy-0.25,
xanchor="center",
yanchor="bottom",
sizex=0.5,
sizey=0.5,
layer='above'
)
fig.show()