繁体   English   中英

Plotly:如何在 Plotly 图形上绘制多个图像?

[英]Plotly: How to plot multiple images on a Plotly figure?

我的主要目标是使用 Dash 的 Plotly 图在气象图上显示天气图标。 此要求的示例如下所示:

天气图标目标

捕获 - 天气图标目标

为此,我尝试编写以下代码:

def graph_pictos(df: pd.DataFrame):
    
    k = 0
    
    fig = go.Figure()

    file_path = 'pictos_png/'
       
    for row in df.itertuples():
        
        picto_number = str(round(row.pictonumber_3h))        
        image_filename = ''.join((file_path, picto_number,'_big.png'))
        picto_image = base64.b64encode(open(image_filename, 'rb').read())
   
        
        fig.add_layout_image(
            go.layout.Image(
                source = 'data:image/png;base64,{}'.format(picto_image.decode()),
                xref = "x",
                yref = "y",
                x = k,
                y = 1,
                sizex = 0.5,
                sizey = 0.5,
                xanchor="center",
                yanchor="middle"
            )
        )
        k+=1
        
   
        
        return fig 

我使用一个图标图像文件夹('pictos_png'),其中每个图像名称都对应一个天气代码。 然后,将数据帧df传递给函数,其中每一行对应于所考虑时间戳的天气代码。 但是,此功能似乎只显示与数据帧df最后一个图标代码相对应的一个天气图标,如下所示:

Plotly 上的图标图像

捕获 - Plotly 上的图标图像

任何人都知道为什么这不能正常工作?

您提供的代码不容易重现。 但是,以下设置应该与您要查找的内容非常接近:

阴谋

在此处输入图片说明

代码

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd

data = {'category': ['A', 'B', 'C', 'D'],
        'x': [4,8,12,16],
        'y':[1,1,1,1],
        'image':["https://images.plot.ly/language-icons/api-home/python-logo.png",
                 "https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png",
                 "https://images.plot.ly/language-icons/api-home/python-logo.png",
                 "https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png"],
        'intervals':[[4, 6], [8, 10], [12, 14], [16, 18]]
       }
df = pd.DataFrame(data)

# Create figure
fig = go.Figure()

for i, x in enumerate(df['x']):

    fig.add_layout_image(
            dict(
                source=df['image'].iloc[i],
                xref="x",
                yref="y",
                x=x,
                y=df['y'].iloc[i],
                sizex=2,
                sizey=2,
                sizing="stretch",
                opacity=0.5,
                layer="below")
    )
fig.update_layout(xaxis_range=[0, 20], yaxis_range=[-2,4])

fig.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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