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

如何为NiceGUI的ui.chart柱状图添加点击事件并实现多图表联动?

解决NiceGUI柱状图点击事件不生效的问题

你的核心问题是柱状图点击事件没触发,不管是直接写JS函数字符串还是绑定Python函数都没起作用。下面给你修正后的实现方式,先搞定点击弹出“hello”,再说明后续更新其他图表的思路。

一、正确绑定点击事件到Python函数

NiceGUI的ui.chart基于Highcharts,得按Highcharts的事件结构绑定,而且NiceGUI支持直接把Python函数绑定到图表事件上,不用手动写JS字符串。

你需要把点击事件绑定到plotOptions.series.point.events.click上,替换掉之前注释的无效写法。修改后的完整代码如下:

from nicegui import ui

async def handleBarClick(event):
    # event参数包含点击点的详细信息,比如event.args['point']['key']就是分类名称(如L-L)
    await ui.run_javascript("alert('hello')")

# 假设results是你已定义好的数据源
results = [15000, 22000, 18000, 28000]

chart = ui.chart({
    'chart': {'type': 'bar', 'backgroundColor': 'rgba(0,0,0,0)'},
    'title': {
        'text': 'Breakdown of Fund Flow',
        'margin': 20,
        'align': 'left',
        'style': {'color': '#CED5DF', 'fontWeight': 'bold', 'fontFamily': 'Michroma'}
    },
    'xAxis': {
        'type': 'category',
        'categories': ['L-L', 'L-O', 'O-L', 'O-O'],
        'labels': {'style': {'color': '#CED5DF'}}
    },
    'yAxis': {
        'title': {'text': 'Amount of Funds', 'style': {'color': '#CED5DF'}},
        'labels': {'style': {'color': '#CED5DF'}},
        'gridLineDashStyle': 'dash'
    },
    'series': [{
        'name': 'Funds',
        'data': results,
        'dataLabels': {'enabled': True, 'style': {'color': '#CED5DF'}, 'format': '${point.y:,.2f}'},
        'borderWidth': 0,
        'dataGrouping': False
    }],
    'tooltip': {
        'useHTML': True,
        'headerFormat': '<table><tr><th>{point.key}</th></tr>',
        'pointFormat': '<tr><td>Amount of Funds: {point.y}</td></tr>' +
                       '<tr><td>Number of Cases: {point.count}</td></tr>',
        'footerFormat': '</table>',
        'valueDecimals': 2,
        'valuePrefix': '$'
    },
    'plotOptions': {
        'series': {
            'bar': {'color': '#db3eb1', 'shadow': {}},
            # 关键:绑定点点击事件到Python函数
            'point': {
                'events': {
                    'click': handleBarClick
                }
            }
        }
    },
    'legend': {'enabled': False},
    'credits': {'enabled': False},
}).classes('w-full h-64')

ui.run()

二、验证事件触发

运行上面的代码,点击任意柱状图,浏览器会弹出“hello”,说明事件已经生效。你可以通过event.args['point']['key']获取点击的分类名称(比如L-L),这是后续更新其他图表的核心数据。

三、后续扩展:点击后更新其他图表

当需要同步更新其他图表时,可按以下步骤操作:

  • 在handleBarClick函数中拿到点击的分类:selected_category = event.args['point']['key']
  • 过滤其他图表的数据源,只保留和selected_category相关的数据
  • 调用目标图表的update方法,传入新的配置(比如更新series的data)

举个简单例子,假设你有第二个图表chart2,可以这样实现同步更新:

# 提前定义chart2和对应的数据源
chart2_data = [8000, 12000, 9000, 15000]
chart_categories = ['L-L', 'L-O', 'O-L', 'O-O']

chart2 = ui.chart({
    # 这里是chart2的初始配置,结构和第一个chart类似
}).classes('w-full h-64')

async def handleBarClick(event):
    selected_category = event.args['point']['key']
    # 过滤chart2的数据源
    filtered_data = [val for idx, val in enumerate(chart2_data) if chart_categories[idx] == selected_category]
    # 更新chart2
    await chart2.update({
        'series': [{
            'data': filtered_data
        }]
    })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:13:10