Bokeh Multi-line with hover

后端 未结 1 990
渐次进展
渐次进展 2021-01-29 09:34

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           


        
相关标签:
1条回答
  • 2021-01-29 09:44

    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.

    0 讨论(0)
提交回复
热议问题