首页 > 解决方案 > 散景图例颜色属性

问题描述

我对图例点的颜色有疑问。它们都是红色的,而它应该在 7 中从红色变为绿色。

在此处输入图像描述

产生最后一张图片的代码是:

from bokeh.models import ColumnDataSource, Label, LabelSet, Range1d, Legend
from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool

df = pd.DataFrame({'pc1': range(11),
                   'pc2': range(10,-1,-1),
                   'Muestra': ['A']*6+['B']*5,
                  'color':['#cf0c0c']*6+['#0dab51']*5},
                  index=range(1,12))

ID = ['{} {}'.format(i+1,j) for i,j in enumerate(df.Muestra)]


source = ColumnDataSource(data=dict(pc1=df.pc1,
                                    pc2=df.pc2, 
                                    color=df.color,
                                    ID=ID,
                                    names=df.index))


p = figure(title='Principal Component Analysis')

p.scatter(x='pc1', y='pc2', size=15, fill_color='color', fill_alpha=0.6, line_color=None, source=source)

labels = LabelSet(x='pc1', y='pc2', text='names',
              x_offset=5, y_offset=5, source=source, render_mode='canvas')

legend=Legend(items=[(ID[i-1],[p.renderers[0]]) for i in df.index])

p.add_layout(legend,'right')
p.add_layout(labels)
    
show(p)

我认为它应该是渲染器属性,但我不确定。

标签: bokehlegend-properties

解决方案


除了手动创建图例,您还可以将“ID”指定legend_field为分散渲染器的。这将自动为您生成一个图例,其中每个条目对应于“ID”列中的每个唯一值:

import pandas as pd

from bokeh.models import ColumnDataSource, Label, LabelSet, Range1d, Legend
from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool

df = pd.DataFrame(
    {
        "pc1": range(11),
        "pc2": range(10, -1, -1),
        "Muestra": ["A"] * 6 + ["B"] * 5,
        "color": ["#cf0c0c"] * 6 + ["#0dab51"] * 5,
    },
    index=range(1, 12),
)

ID = ["{} {}".format(i + 1, j) for i, j in enumerate(df.Muestra)]


source = ColumnDataSource(
    data=dict(pc1=df.pc1, pc2=df.pc2, color=df.color, ID=ID, names=df.index)
)


p = figure(title="Principal Component Analysis")

p.scatter(
    x="pc1",
    y="pc2",
    size=15,
    fill_color="color",
    fill_alpha=0.6,
    line_color=None,
    source=source,
    legend_field="ID"   # New kwarg added here
)

labels = LabelSet(
    x="pc1",
    y="pc2",
    text="names",
    x_offset=5,
    y_offset=5,
    source=source,
    render_mode="canvas",
)

# Removed these 2 lines
# legend=Legend(items=[(ID[i-1],[p.renderers[0]]) for i in df.index])
# p.add_layout(legend,'right')

p.add_layout(labels)

show(p)

我最终得到了这个情节: 在此处输入图像描述


推荐阅读