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

如何自定义PyGal WorldMap图表的Tooltip,仅展示国家名与视频数量?

解决Pygal世界地图Tooltip冗余内容问题

要消除Pygal世界地图Tooltip里的冗余内容,自定义成你想要的两种样式之一,只需给图表绑定自定义Tooltip格式化函数即可,具体步骤如下:

1. 定义对应样式的格式化函数

根据你需要的样式选择:

样式一(换行显示国家名和视频数)

def tooltip_style1(x_val, y_val, series_val, country_name):
    return f"{country_name}<br>{y_val} videos"

样式二(单行冒号分隔)

def tooltip_style2(x_val, y_val, series_val, country_name):
    return f"{country_name}: {y_val} videos"

2. 绑定函数到图表对象

在渲染图表前,把自定义函数赋值给你的世界地图图表对象的tooltip_formatter属性:

# 这里选样式一为例,换成tooltip_style2就是样式二
worldmap_chart.tooltip_formatter = tooltip_style1

3. 调整渲染代码(可选)

移除渲染参数里的print_values=True(它会触发默认的数值显示,可能加重冗余),最终渲染代码如下:

worldmap_chart.render_to_file('worldmap_result.svg', 
                              show_legend=True, 
                              human_readable=True, 
                              fill=True, 
                              print_labels=True, 
                              no_data_text="No data available", 
                              legend_at_bottom=True, 
                              pretty_print=True,
                              x_title="Hover the cursor on the country's name bellow or the map above:",
                              force_uri_protocol='https')

原理说明

Pygal的tooltip_formatter属性允许你传入自定义函数,完全接管Tooltip的内容生成。函数的四个参数中,country_name是格式化后的国家名称,y_val是你传入的视频数量,返回的字符串支持HTML标签(比如<br>实现换行),这样就能精准控制Tooltip显示内容,彻底去掉默认的冗余信息。

内容的提问来源于stack exchange,提问作者Marco Aurelio Fernandez Reyes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:54:22