【问题标题】:How to add images instead of dots in a plotly scatter plot (python) [duplicate]如何在散点图中添加图像而不是点(python)[重复]
【发布时间】:2021-12-31 07:25:14
【问题描述】:

假设我有这个散点图:

import plotly.express as px
fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig.show()

但我想在这些特定位置添加不同的图像,而不是点。像这样的:

情节可以吗?我知道你可以add Images 但我不知道如何传递应该显示图像的位置的确切坐标。

感谢您的宝贵时间!谢谢。

【问题讨论】:

    标签: python image plotly add


    【解决方案1】:
    • 关于回答的几点
      • 没有提供图片参考,所以从kaggle下载了一些。找不到表情符号。这会增加执行此操作的代码...
      • Plotly Express 在没有数据框的情况下使用。所以一直坚持这一点。这意味着循环遍历跟踪中的 x&y 值以获取图像的位置
      • 有效使用的图像是随机的,可以根据数据的特征进行选择

    import plotly.express as px
    import kaggle.cli
    import sys, requests
    from pathlib import Path
    from zipfile import ZipFile
    import urllib
    from PIL import Image
    
    # fmt: off
    # download some images to demonstrate
    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")
    
    fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
    
    # question did not use a dataframe,  so will use x & y from the figure trace
    # just a selection of images, used NFL images given don't have emojis
    for x,y, png in zip(fig.data[0].x, fig.data[0].y, Path.cwd().joinpath("nfl-logos").glob("*.png")):
        fig.add_layout_image(
            x=x,
            y=y,
            source=Image.open(png),
            xref="x",
            yref="y",
            sizex=2,
            sizey=2,
            xanchor="center",
            yanchor="middle",
        )
        
    fig
    

    【讨论】:

    • 非常感谢!这对我帮助很大!
    猜你喜欢
    • 2020-06-26
    • 2014-12-14
    • 2021-01-28
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    相关资源
    最近更新 更多