首页 > 解决方案 > 如何使用 python Bokeh 绘制圆形图 LinearColorMapper

问题描述

使用以下代码,

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)

我可以制作一个圆形图,为物种着色:

在此处输入图像描述

但我想做的是根据petal_length.

我尝试了这段代码但失败了:

from bokeh.models import LinearColorMapper
exp_cmap = LinearColorMapper(palette='Viridis256', low = min(flowers["petal_length"]), high = max(flowers["petal_length"]))

p.circle(flowers["petal_length"], flowers["petal_width"], 
         fill_color = {'field'  : flowers["petal_lengh"], 'transform' : exp_cmap})

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

show(p)

而且在最终所需的情节中,如何放置显示值范围和分配值的颜色条。像这样的东西:

在此处输入图像描述

我正在使用Python 2.7.13.

标签: pythonplotbokeh

解决方案


为了回答您的第一部分,有一个小错字(petal_lengh而不是petal_length),但更重要的是,使用bokeh.ColumnDataSource将解决您的问题(我尝试在没有CDS并且只得到列错误的情况下这样做):

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

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

source = ColumnDataSource(flowers)

exp_cmap = LinearColorMapper(palette="Viridis256", 
                             low = min(flowers["petal_length"]), 
                             high = max(flowers["petal_length"]))

p.circle("petal_length", "petal_width", source=source, line_color=None,
        fill_color={"field":"petal_length", "transform":exp_cmap})

# ANSWER SECOND PART - COLORBAR
# To display a color bar you'll need to import 
# the `bokeh.models.ColorBar` class and pass it your mapper.
from bokeh.models import ColorBar
bar = ColorBar(color_mapper=exp_cmap, location=(0,0))
p.add_layout(bar, "left")

show(p)

在此处输入图像描述

另请参阅:https ://github.com/bokeh/bokeh/blob/master/examples/plotting/file/color_data_map.py


推荐阅读