散景图例颜色属性

Bokeh legend color properties

我对图例点的颜色有疑问。它们都是红色的,而它应该在 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)

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

您需要为图例项设置一个 explicit index,以告诉它们您希望它们为哪一行绘制。否则默认情况下,图例项仅根据渲染器数据源第一行中的数据绘制。

LegendItem(label="some text", renderers=[r], index=i),

除了手动创建图例,您还可以将“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)

我最终得到了这个情节: