Bokeh Multi-line with hover

你离开我真会死。 提交于 2019-12-13 09:36:29

问题


I have pandas dataframe which looks like this

           'A' 'B' 'C'
2018/1/1    10  20  20
2018/1/2    34  13  23
2018/1/3    23  45  43
2018/1/4    14  98  76
2018/1/5    58  65  57 

How do I convert this to columnDataSource ? How do I create a multi-line graph in bokeh with hover tool. X-axis as the date


回答1:


Imports:

import pandas as pd
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.plotting import figure, show, output_notebook
output_notebook()

Here's the data as you present it:

days = ['2018/1/1', '2018/1/2', '2018/1/3', '2018/1/4', '2018/1/5']
data_a = [10, 34, 23, 14, 58]
data_b = [20, 13, 45, 98, 65]
data_c = [20, 23, 43, 76, 57]

Create DataFrame:

df_plot = pd.DataFrame({'A': data_a, 'B': data_b, 'C': data_c}, index=days)

             A   B   C
2018/1/1    10  20  20
2018/1/2    34  13  23
2018/1/3    23  45  43
2018/1/4    14  98  76
2018/1/5    58  65  57

However, the index is not a proper datetime format, so create a dates column with the proper format:

df_plot['dates'] = pd.to_datetime(df_plot.index, format='%Y/%m/%d')

             A   B   C       dates
2018/1/1    10  20  20  2018-01-01
2018/1/2    34  13  23  2018-01-02
2018/1/3    23  45  43  2018-01-03
2018/1/4    14  98  76  2018-01-04
2018/1/5    58  65  57  2018-01-05

Now for the plotting:

source = ColumnDataSource(df_plot)
p = figure(x_axis_type="datetime")
p.line('dates', 'A', source=source, color='red')
p.line('dates', 'B', source=source, color='blue')
p.line('dates', 'C', source=source, color='green')
p.add_tools(HoverTool(tooltips=[("A", "@A"), ("B", "@B"), ("C", "@C")]))
show(p)

This is just a png, the actual output will have hoover tools.



来源:https://stackoverflow.com/questions/52120838/bokeh-multi-line-with-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!