散景散点图中的色点 [英] Color points in scatter plot of Bokeh
问题描述
我有以下简单的pandas.DataFrame
:
df = pd.DataFrame(
{
"journey": ['ch1', 'ch2', 'ch2', 'ch1'],
"cat": ['a', 'b', 'a', 'c'],
"kpi1": [1,2,3,4],
"kpi2": [4,3,2,1]
}
)
我将其绘制如下:
import bokeh.plotting as bpl
import bokeh.models as bmo
bpl.output_notebook()
source = bpl.ColumnDataSource.from_df(df)
hover = bmo.HoverTool(
tooltips=[
("index", "@index"),
('journey', '@journey'),
("Cat", '@cat')
]
)
p = bpl.figure(tools=[hover])
p.scatter(
'kpi1',
'kpi2', source=source)
bpl.show(p) # open a browser
我无法根据cat
对点进行颜色编码.最终,我希望第一个点和第三个点使用相同的颜色,第二个点和第四个点使用另外两种不同的颜色.
I am failing to color code the dots according to the cat
. Ultimately, I want to have the first and third point in the same color, and the second and fourth in two more different colors.
如何使用Bokeh实现此目的?
How can I achieve this using Bokeh?
推荐答案
这是在某种程度上避免手动映射的方法.我最近在此github问题上偶然发现了bokeh.palettes
CategoricalColorMapper
在此问题中.这种方法将它们结合在一起.在此处和CategoricalColorMapper
看到可用调色板的完整列表.详细信息此处.
Here's a way that avoids manual mapping to some extent. I recently stumbled on bokeh.palettes
at this github issue, as well as CategoricalColorMapper
in this issue. This approach combines them. See the full list of available palettes here and the CategoricalColorMapper
details here.
我在使它直接在pd.DataFrame
上运行时遇到问题,并且还发现使用您的from_df()
调用它不起作用. 文档显示直接传递DataFrame
,对我有用.
I had issues getting this to work directly on a pd.DataFrame
, and also found it didn't work using your from_df()
call. The docs show passing a DataFrame
directly, and that worked for me.
import pandas as pd
import bokeh.plotting as bpl
import bokeh.models as bmo
from bokeh.palettes import d3
bpl.output_notebook()
df = pd.DataFrame(
{
"journey": ['ch1', 'ch2', 'ch2', 'ch1'],
"cat": ['a', 'b', 'a', 'c'],
"kpi1": [1,2,3,4],
"kpi2": [4,3,2,1]
}
)
source = bpl.ColumnDataSource(df)
# use whatever palette you want...
palette = d3['Category10'][len(df['cat'].unique())]
color_map = bmo.CategoricalColorMapper(factors=df['cat'].unique(),
palette=palette)
# create figure and plot
p = bpl.figure()
p.scatter(x='kpi1', y='kpi2',
color={'field': 'cat', 'transform': color_map},
legend='cat', source=source)
bpl.show(p)
这篇关于散景散点图中的色点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!