如何在Python的Bokeh圆图中添加图例

sca*_*der 4 python plot bokeh

我有以下代码:

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

colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in flowers['species']]

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

p.circle(flowers["petal_length"], flowers["petal_width"],
         color=colors, fill_alpha=0.2, size=10)

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

show(p)
Run Code Online (Sandbox Code Playgroud)

哪个产生这个情节

在此处输入图片说明

如何根据图的圆圈颜色添加图例?哪里:

  • setosa:红色
  • 杂色:绿色
  • 弗吉尼亚:蓝色

jos*_*oto 5

想到的最简单的方法是为要向其传递数据的绘图定义ColumnDataSource,然后从此处引用带有 "species"来自数据框的数据。

这是使用此解决方案的代码重做:

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

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

colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in flowers['species']]
flowers['colors'] = colors

source = ColumnDataSource(flowers)

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

p.circle("petal_length", "petal_width",
         color='colors', fill_alpha=0.2, size=10, legend='species',source=source)
p.legend.location = "top_left"

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

show(p)
Run Code Online (Sandbox Code Playgroud)

这就是您应该获得的。我另外将图例放在右边,这样它就不会插入到图的顶部:

绘制解决方案