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

如何在Python的Bokeh圆形散点图内添加图例

如何给Bokeh圆形散点图添加图例

嘿,我来帮你搞定这个图例的问题!你现在的代码是把所有鸢尾花的数据一次性绘制出来,Bokeh没办法自动区分不同物种来生成对应的图例。咱们只需要稍微调整一下,按物种分类单独绘制散点,就能轻松添加清晰的图例啦。

下面是修改后的完整代码:

from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.iris import flowers

# 保留你的颜色映射
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}

p = figure(title = "Iris Morphology")
p.xaxis.axis_label = 'Petal Length'
p.yaxis.axis_label = 'Petal Width'

# 关键:按物种循环,分别绘制每个类别的散点,并指定图例标签
for species, color in colormap.items():
    # 筛选当前物种的数据
    species_data = flowers[flowers['species'] == species]
    # 绘制散点,添加legend_label参数
    p.circle(
        species_data["petal_length"], 
        species_data["petal_width"], 
        color=color, 
        fill_alpha=0.2, 
        size=10,
        legend_label=species  # 这行是生成图例的核心
    )

# 可以调整图例的位置,让图表更美观
p.legend.location = "top_left"
# 还可以给图例加个标题
p.legend.title = "Species"

output_file("iris.html", title="iris.py example")
show(p)

关键说明:

  • 原来的代码把所有点一次性绘制,Bokeh无法识别不同类别的分组,所以没有图例。现在通过循环每个物种,单独绘制对应的数据点,同时给每个circle()调用加上legend_label参数,Bokeh就会自动为每个物种生成图例项。
  • p.legend.location用来设置图例的位置,可选值还有"top_right"、"bottom_left"等,你可以根据图表数据分布选择最合适的位置。
  • 添加p.legend.title可以给图例加上标题,让图表的可读性更强。

这样修改后,你打开生成的iris.html就能看到带有清晰物种图例的散点图啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:24:50