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

Bokeh绘制10+温度曲线异常问题排查求助

问题根源分析

你遇到的核心问题是ColumnDataSource中列长度不一致:
在simulation函数里,你将clim_name、Moy_Tr等长度为曲线数量的列表放入了source_data,但date和Tr_*列的长度是时间点数量(远大于曲线数量)。Bokeh要求数据源的所有列必须长度相同,这种不一致会导致数据被截断、坐标轴缩放异常,当曲线数量达到10时,异常表现完全显现。

解决方案

步骤1:修改simulation函数,移除数据源中长度不匹配的列

不需要将clim_name、Moy_Tr等非绘图数据放入ColumnDataSource,直接将它们作为参数传递给绘图函数:

def simulation(pays, batterie, container, fenetre, chemin_accès_soll, chemin_accès_temp):
    if fenetre and isinstance(fenetre, Tk):
        fenetre.destroy()

    results = run_simulation(pays, batterie, container, chemin_accès_soll, chemin_accès_temp)

    source_data = {"date": results["dates"][0]}

    for i, temperatures in enumerate(results["temperatures"]):
        source_data[f'Tr_{i + 1}'] = temperatures

    # 移除长度不匹配的列,避免数据源异常
    source = ColumnDataSource(data=source_data)
    # 直接传递曲线名称和均值参数
    afficher_graphique(source, results["clim_names"], results["moyenne_Tr"])

    check_simulation_data(results)

步骤2:修改afficher_graphique函数,接收外部传递的曲线名称

不再从数据源中读取clim_name,改用函数参数传入:

def afficher_graphique(source, clim_names, moyenne_values):
    output_file("graphique.html")

    p = figure(title="Température Rack", x_axis_label='Date', y_axis_label='T°C_rack', plot_width=1500, plot_height=300)
    renderers = []

    # 使用Bokeh内置调色板避免颜色重复和索引越界
    from bokeh.palettes import Category20
    color = Category20[len(clim_names)] if len(clim_names) <=20 else Category20[20] + ['#888888']*(len(clim_names)-20)

    for i, clim_name in enumerate(clim_names):
        column_name = f'Tr_{i + 1}'
        if column_name in source.data:
            line_color = color[i]
            line = p.line('date', column_name, source=source, line_color=line_color)
            renderers.append(line)

    p.xaxis.formatter = DatetimeTickFormatter(days="%d/%m/%y")

    legend_items = [(clim_name, [line]) for clim_name, line in zip(clim_names, renderers)]
    legend_items_with_values = [(f"{clim_name} ({moyenne_value}°C)", line)
        for (clim_name, line), moyenne_value in zip(legend_items, moyenne_values)]

    legend = Legend(items=legend_items_with_values, location="center")
    p.add_layout(legend, 'right')

    hover = HoverTool(tooltips=[('Value', '$y')])
    tool_list = [hover]
    p.add_tools(*tool_list)

    show(p, notebook_handle=True)

额外优化

  • 替换了手动写的颜色列表,使用Bokeh内置的Category20调色板,避免颜色重复和索引越界问题;
  • 确保所有Tr_*列的长度与date列完全一致(你已确认数据长度无差异,这部分无需额外修改)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:44:55