首页 > 解决方案 > 根据散景散点图中 ColumnDataSource 中的值设置颜色

问题描述

我在 Bokeh 中使用 pandas 数据框作为 ColumnDataSource 来绘制散点图,其中每个气泡代表一个国家。在我的数据框中,有一个名为“区域”的列,用于通知每个国家/地区的区域,我希望气泡的颜色与其区域相对应。我想使用调色板(如 Viridis)来做到这一点,但我很难理解它在 Bokeh 中是如何工作的,因为我更习惯于 MPL。

source = ColumnDataSource(data=dict(x=df['gdp'], 
                                y=df['lifeExpec'], 
                                s=df['population']/100000))

p = figure(title='Bokeh Bubble Chart',
       width=600,
       height=500,
       x_axis_type='linear',
       y_axis_type='linear',
       x_range=(1000, 90000), 
       y_range=(0, 100))

p.scatter(source=source,
      x='x',
      y='y',
      radius = 's',
      marker="circle",
      alpha = 0.5)

show(p)

标签: pythonpython-3.xbokeh

解决方案


知道了。将所有区域存储在我的字典中的一个变量中,然后使用 factor_cmap 为每个区域设置颜色。

regions = df['region']

source = ColumnDataSource(data=dict(x=df2['gdp'], 
                                y=df2['lifeExpec'], 
                                s=df2['population']/100000,
                                ur = regions))

colors = factor_cmap('ur', palette=Category20b_20, factors=regions.unique()) 

p.scatter(source=source,
          x='x',
          y='y',
          radius = 's',
          marker="circle",
          alpha = 0.5,
          fill_color=colors,
          line_color=colors)

在此处输入图像描述


推荐阅读