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

Holoviews中为条形图创建DynamicMap后添加选项时程序崩溃

Holoviews DynamicMap添加可选值后崩溃的解决办法

问题重现

以下代码可正常生成指定国家的条形图,但取消注释最后一行设置redim.values后程序崩溃,抛出TypeError: list.remove() takes exactly one argument (0 given)错误:

# imports
import pandas as pd
import numpy as np
import holoviews as hv

# loading holoviews engine
hv.extension('matplotlib') #('bokeh')

# creating dummy data
samples = 1000
countries_sample = np.random.choice(['GBR', 'ITA'], samples)
hours_sample = np.random.choice(list(range(0,23)), samples)
count = np.random.randint(1, 5, size=samples)

df_test = pd.DataFrame({'location_country_iso3': countries_sample, 'hour': hours_sample, 'Count': count})
df_test = df_test.groupby(['location_country_iso3', 'hour']).size() 

# function to draw output
def draw_bars(country):
    return hv.Bars(df_test).sort().select(location_country_iso3 = country)

# dynamic map out of the function, to select single country
dmap_bars = hv.DynamicMap(draw_bars, kdims = ['country'])

# specific country selection
dmap_bars['GBR']

## options for country selection (this breaks):
# dmap_bars.redim.values(country = ['GBR', 'ITA'])

解决方法

修改draw_bars函数,提取对应国家的数据后,只保留hour作为条形图的维度,避免多余维度干扰渲染:

def draw_bars(country):
    # 提取对应国家的数据,重置索引并命名计数列
    country_data = df_test.loc[country].reset_index(name='Count')
    # 仅以hour为x轴维度创建条形图
    return hv.Bars(country_data, kdims='hour', vdims='Count').sort()

之后执行dmap_bars.redim.values(country=['GBR', 'ITA'])即可正常生成带国家选择器的动态图表。

原因说明

原代码中,hv.Bars(df_test)会将MultiIndex的location_country_iso3和hour都作为图表维度,即使通过select筛选出单个国家,该维度仍然存在。Holoviews在渲染DynamicMap切换时,处理这个多余的单值维度会导致内部艺术家对象的列表操作出错,从而抛出无参数的list.remove()错误。修改后的数据仅保留hour作为维度,避免了这一冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:57:09