基于年的散景颜色

时间:2018-06-13 15:20:19

标签: python pandas bokeh

所以我基本上得到了这段代码:

import pandas as pd
from bokeh.plotting import figure, ColumnDataSource
from bokeh.io import show, output_file
import bokeh.models as bmo

data = {
        'ranking': df['ranking'],
        'pct_intl_student' : df['pct_intl_student'],
        'years': year_list,
        'color': colors,
        'university':df['university_name']
}

source = ColumnDataSource(data)
hover = bmo.HoverTool(
            tooltips=[('year', '@years'),
                      ('ranking', '@ranking'),
                      ('% Int. Stu.', '@pct_intl_student'),
                      ('University', '@university')])



p = figure(tools=[hover], title="Scatterplot: International Students")
p.xaxis.axis_label = 'International Ranking'
p.yaxis.axis_label = 'Pct. International Students'

p.scatter('ranking', 'pct_intl_student', source=source)

show(p)

其中color基本上是一个列表,其颜色与排名中的每个数据点和pct_intl_student相对应。基本上,它们的长度相同。是否可以确保我在散点图中绘制的每个数据点都具有颜色列表中指定的颜色?我认为它只是图中的一些属性,但在文档中无法找到它。从数据框中检索所有数据,我创建了颜色映射:

colormap = {2016: 'red',
            2017: 'green',
            2018: 'blue'}
colors = [colormap[x] for x in df['year']]

1 个答案:

答案 0 :(得分:1)

好的,所以我提出了这个问题,但我想出了问题:

p.scatter('ranking', 'pct_intl_student', source=source)

你应该添加:color ='color'。

所以它看起来像这样:

p.scatter('ranking', 'pct_intl_student', source=source, color='color')

为了完成这里,我们整个代码片段都有编辑:

colormap = {2016: 'red',
            2017: 'green',
            2018: 'blue'}
colors = [colormap[x] for x in df['year']]

data = {
        'ranking': df['ranking'],
        'pct_intl_student' : df['pct_intl_student'],
        'years': year_list,
        'color': colors,
        'university':df['university_name']
}

source = ColumnDataSource(data)
hover = bmo.HoverTool(
            tooltips=[('year', '@years'),
                      ('ranking', '@ranking'),
                      ('% Int. Stu.', '@pct_intl_student'),
                      ('University', '@university')])



p = figure(tools=[hover], title="Scatterplot: International Students")
p.xaxis.axis_label = 'International Ranking'
p.yaxis.axis_label = 'Pct. International Students'

p.scatter('ranking', 'pct_intl_student', source=source, color='color')

show(p)