我正在尝试从看起来像这样的数据框中绘制一个简单的热图:
row column content amount
0 x a c1 1
2 x b c3 3
4 x c c2 1
6 y a c1 1
8 y b c3 3
10 y c c2 1
12 z a c1 1
14 z b c3 3
16 z c c2 1
row
和column
表示单元格的位置,应根据content
选择单元格的颜色,我希望工具提示显示content
和{{ 1}}。
我目前这样尝试(使用bokeh 1.2.0):
amount
但是,有两个问题:
有什么想法吗?
2)当我超过import pandas as pd
from bokeh.io import show
from bokeh.models import CategoricalColorMapper, LinearColorMapper, BasicTicker, PrintfTickFormatter, ColorBar, ColumnDataSource
from bokeh.plotting import figure
from bokeh.palettes import all_palettes
from bokeh.transform import transform
df = pd.DataFrame({
'row': list('xxxxxxyyyyyyzzzzzz'),
'column': list('aabbccaabbccaabbcc'),
'content': ['c1', 'c2', 'c3', 'c1', 'c2', 'c3'] * 3,
'amount': list('123212123212123212')})
df = df.drop_duplicates(subset=['row', 'column'])
source = ColumnDataSource(df)
rows = df['row'].unique()
columns = df['column'].unique()
content = df['content'].unique()
colors = all_palettes['Viridis'][max(len(content), 3)]
mapper = CategoricalColorMapper(palette=colors, factors=content)
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
p = figure(title="My great heatmap",
x_range=columns, y_range=rows,
x_axis_location="above", plot_width=600, plot_height=400,
tools=TOOLS, toolbar_location='below',
tooltips=[('cell content', '@content'), ('amount', '@amount')])
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "5pt"
p.axis.major_label_standoff = 0
p.rect(x="row", y="column", width=1, height=1,
source=source,
fill_color=transform('content', mapper))
# color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="5pt",
# location=(0, 0))
# p.add_layout(color_bar, 'right')
show(p)
部分时,我收到一条错误消息:
ValueError:预期为ContinuousColorMapper类型的实例,得到了 CategoricalColorMapper类型的CategoricalColorMapper(id ='3820',...)
我在做什么错了?
答案 0 :(得分:1)
您的 x 和 y 坐标已互换,应为:
p.rect(x="column", y="row", ...)
对于其他消息,它是不言自明的:从散景1.2开始,ColorBar
只能配置连续的颜色映射器(例如LinearColorMapper
)。您可以:
source
中加入一列颜色,或者LinearColorMapper
(即将content
映射到某个数字比例)答案 1 :(得分:0)
对于您的colorBar,解决方案就在这里,我安静不明白,您的源发生了什么,我会再深入一点。 colorBar需要一个连续的映射器,您对其进行了分类。
from bokeh.models import (CategoricalColorMapper, LinearColorMapper,
BasicTicker, PrintfTickFormatter, ColorBar, ColumnDataSource,
LinearColorMapper)
factors =df['content'].unique().tolist()
colors = all_palettes['Viridis'][max(len(factors), 3)]
mapper = LinearColorMapper(palette=colors)