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

多索引Pandas DataFrame绘图:动态添加列对应图例求助

Adding Legends to Your Bokeh Multi-Index Line Plot

Got it, let's figure out how to add clear, functional legends to your dynamic multi-index line plot. Since you're using Bokeh (from the figure() call you mentioned), here's a straightforward approach tailored to your setup:

1. Core Idea: Assign Legend Labels When Plotting Each Line

The key is to explicitly set the legend_label parameter every time you call p.line(). This ties each line to a readable label in the legend. Since your columns are dynamic, you can loop through your target columns and generate labels on the fly.

2. Full Example Code (Integrated with Your Setup)

Here's how to adapt your existing code:

from bokeh.plotting import figure, show
import pandas as pd

# Your existing setup starts here
p = figure(x_axis_type="datetime", title="Dynamic Multi-Index Plot")
table = pivot_table(...)  # Your pivot logic for the multi-index DataFrame

# Define your dynamic columns (replace with your query-generated list)
dynamic_cols = [10, 11, 12, 21, 26, 27]

# Loop through each dynamic column to plot lines and add legend entries
for col in dynamic_cols:
    # If your table has single-level columns after pivot:
    p.line(
        x=table.index,
        y=table[col],
        legend_label=f"Column {col}",  # Customize this label to be meaningful
        line_width=2
    )

    # If your table has multi-level columns (e.g., (category, col)), use this instead:
    # for category in table[col].columns:
    #     p.line(
    #         x=table.index,
    #         y=table[col][category],
    #         legend_label=f"{category} - Col {col}",
    #         line_width=2
    #     )

# Customize the legend's appearance and behavior
p.legend.location = "top_right"  # Choose a position that doesn't block your plot
p.legend.click_policy = "hide"  # Optional: Let users click legend items to hide lines
p.legend.label_text_font_size = "10pt"  # Adjust font size for readability

show(p)

3. Key Notes

  • Dynamic Labels: The legend_label can be any string—feel free to include more context from your multi-index (like category names) to make it clearer for users.
  • Legend Customization: Use p.legend properties to tweak position, font size, background color, and more. The click_policy is a nice touch for interactive plots.
  • Multi-Index Columns: If your pivoted table has nested columns, loop through each level to create unique labels for every line (as shown in the commented section).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:46:47