【问题标题】:How can I change the symbol of a plotly scatterplot to a svg file如何将绘图散点图的符号更改为 svg 文件
【发布时间】:2021-12-27 03:34:36
【问题描述】:

我正在尝试制作一个散点图的点是棋子的图表。现在代码很简单:

fig = px.scatter(
    x = df_game.x, 
    y = df_game.y,
    color = df_game.color,
    symbol = df_game.icon,
    opacity = 0.1
    )
fig.show()

它返回这个图表:

但我想要这样的东西:

我的数据框包含每个回合中每个棋子的 (x, y) 位置,如下所示:

   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

我要使用的图标在icon列中。

如何将默认图标更改为我的 .svgs?

【问题讨论】:

  • 如果文件格式是png的话,很容易处理。看看我的过去examples

标签: python plotly data-visualization scatter-plot plotly-python


【解决方案1】:

我能够将 SVG 图像转换为 PNG 图像并显示它。要安装的库是“cariosvg”。使用它将转换后的二进制转换为base64中的字符串并将其设置为图像的参考。

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()

【讨论】:

  • Size xy是控制要引入的图片大小的参数,所以如果图片比较小,就加大数值。如果我的回答对你有帮助,请采纳。
猜你喜欢
  • 1970-01-01
  • 2020-06-20
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 2020-10-12
  • 2019-05-19
相关资源
最近更新 更多