我有以下代码:
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)
产生这个情节
如何根据圆圈的颜色向图表添加图例? 地点:
答案 0 :(得分:3)
最简单的方法是将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)
这就是你应该得到的。我还将图例放在右边,因此它没有插在图表的顶部:
答案 1 :(得分:1)
您可以使用for循环绘制它:
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'
for specie in colormap.keys():
df = flowers[flowers['species']==specie]
p.circle(df["petal_length"], df["petal_width"],
color=colormap[specie], fill_alpha=0.2, size=10, legend=specie)
p.legend.location = "top_left"
output_file("iris.html", title="iris.py example")
show(p)