You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bokeh绘制UMAP图时图例仅显单个条目,如何展示全部8个种群?

解决Bokeh UMAP图图例不全及布局调整问题

问题分析

你当前的代码中,scatter方法直接传入整个DataFrame的列数据,且legend_label设为固定字符串,导致Bokeh将所有点归为同一个图例条目。要显示全部8个种群的图例,需要让Bokeh按population字段分组识别不同类别。

修正后的代码

import numpy as np
import pandas as pd
import bokeh.plotting as bp
from bokeh.plotting import ColumnDataSource, figure, show
from umap import UMAP

# 数据读取与预处理部分保持不变
umap = pd.read_csv("SGDP_download/SGDP_bi_snps_norm-2.eigenvec", sep="\t")
umap.rename(columns={"#IID": "#ID"}, inplace=True)

loc = pd.read_csv("SGDP_download/pca_loc_fix_python-order.txt")
colors = pd.read_csv("SGDP_download/bokeh_colors.txt")

eigenval = pd.read_csv("SGDP_download/SGDP_bi_snps_norm-2.eigenval", header=None)
pve = round(eigenval / (eigenval.sum(axis=0))*100, 2)

umap.sort_values('#ID', inplace=True)
umap.insert(loc=1, column='#LOC', value=loc)
umap.rename(columns={'#ID': 'ID', '#LOC': 'LOC'}, inplace=True)

regions_umap = umap.iloc[:, 2:12]

umap_plot = UMAP(n_components=2, init="random", random_state=15)
umap_proj = umap_plot.fit_transform(regions_umap)

df = pd.DataFrame(umap_proj, columns=['UMAP1', 'UMAP2'])
df.insert(loc=0, column='population', value=loc)
df.insert(loc=1, column='color', value=colors)
df.index = umap["ID"]

source = ColumnDataSource(df)

TOOLS="hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select,examine,help"

fig = figure(tools=TOOLS, x_axis_label='UMAP1', y_axis_label='UMAP2')
# 关键修改:绑定数据源,按population字段自动生成图例
fig.scatter(x='UMAP1', y='UMAP2', color='color', size=5, 
            legend_field='population', fill_alpha=0.6, line_color=None,
            source=source)

# 图例布局调整
fig.legend.location = "bottom_center"  # 图例移至底部居中
fig.legend.title = "metapopulations"
fig.legend.title_text_align = "center"  # 图例标题居中
fig.legend.ncols = 4  # 图例分4列排列,避免横向拥挤

show(fig)

关键修改说明

  • 图例生成逻辑:替换legend_label为legend_field='population',并绑定ColumnDataSource,Bokeh会自动根据population的不同取值生成对应图例条目及颜色。
  • 图例布局优化:
    • fig.legend.location = "bottom_center":将图例定位到图表底部居中位置
    • fig.legend.title_text_align = "center":设置图例标题居中显示
    • fig.legend.ncols = 4:拆分图例为多列,避免单行列数过多导致布局混乱(可根据需求调整列数)

内容的提问来源于stack exchange,提问作者Matteo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:16:22