You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly中使用Flagpy添加国旗图标失败求助

解决Plotly条形图旁显示国旗的问题

问题分析

你的代码存在几个关键问题导致国旗无法正常显示:

  1. 未导入PIL.Image模块却调用了Image.open(),且Plotly的layout_image支持直接传入图片URL/本地路径,无需额外转换
  2. 分类y轴下,yref设为"y"会导致位置匹配错误,需改用"y domain"
  3. sizex和sizey的单位设置不符合当前轴类型,分类轴下应使用相对域值,x轴方向的尺寸要匹配数值范围
  4. 国旗的位置偏移量需要调整,确保显示在目标数值旁

修改后的代码

import plotly.graph_objects as go
import pandas as pd
import flagpy as fp

# 数据准备
df_date_top_n = pd.DataFrame({
    'CTR_DSC': ['Spain', 'Canada', 'Germany'],
    'PLT_NAM_DSC': ['Plant A', 'Plant B', 'Plant C'],
    'KPI_VAL': [100, 200, 150],
    'flag_emoji': ['🇪🇸', '🇨🇦', '🇩🇪']
})

df_date_top_n.sort_values('KPI_VAL', ascending=True, inplace=True)

# 创建图表
fig = go.Figure()

# 添加条形图
fig.add_trace(go.Bar(
    x=df_date_top_n['KPI_VAL'],
    y=df_date_top_n['PLT_NAM_DSC'],
    orientation='h',
    text=df_date_top_n['KPI_VAL'],
    textposition='auto',
    opacity=0.8,
))

# 添加国旗图片
for idx, row in df_date_top_n.iterrows():
    flag_url = fp.get_flag_img(row['CTR_DSC'])
    # 计算分类y轴对应的domain位置(总共有3个分类,索引从0到2,domain范围0-1)
    y_pos = (idx) / len(df_date_top_n) + 1/(2*len(df_date_top_n))
    
    fig.add_layout_image(
        dict(
            source=flag_url,  # 直接传入图片URL/路径,无需PIL转换
            xref="x", 
            yref="y domain",  # 使用domain匹配分类y轴
            x=row['KPI_VAL'] + 10,  # 调整x偏移,显示在数值右侧
            y=y_pos,
            sizex=15,  # x轴方向尺寸(匹配MWH数值范围)
            sizey=0.15,  # y轴方向相对尺寸(domain范围0-1)
            xanchor="left", 
            yanchor="middle",
            sizing="contain",
            opacity=0.8,
            layer="above"
        )
    )

# 布局设置
fig.update_layout(
    title='Top Plant Consumption',
    xaxis_title="MWH",
    yaxis_title="Factory Name",
    xaxis_range=[0, df_date_top_n['KPI_VAL'].max() + 30]  # 扩展x轴范围,避免国旗超出显示区域
)

fig.show()

额外说明

如果flagpy返回的是本地图片路径,确保路径正确可访问;若返回的是网络URL,需保证网络环境能正常加载该图片。你也可以直接使用DataFrame里的flag_emoji列,把国旗表情作为条形图的text或hovertext,实现更简单的国旗显示效果。

内容的提问来源于stack exchange,提问作者Carles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:37:44