How do I use custom labels for ticks in Bokeh?

前端 未结 2 1855
耶瑟儿~
耶瑟儿~ 2020-11-30 09:02

I understand how you specify specific ticks to show in Bokeh, but my question is if there is a way to assign a specific label to show versus the position. So for example

2条回答
  •  遥遥无期
    2020-11-30 09:32

    As of even more recent versions of Bokeh (0.12.14 or so) this is even simpler. Fixed ticks can just be passed directly as the "ticker" value, and major label overrides can be provided to explicitly supply custom labels for specific values:

    from bokeh.io import output_file, show
    from bokeh.plotting import figure
    
    p = figure()
    p.circle(x=[1,2,3], y=[4,6,5], size=20)
    
    p.xaxis.ticker = [1, 2, 3]
    p.xaxis.major_label_overrides = {1: 'A', 2: 'B', 3: 'C'}
    
    output_file("test.html")
    
    show(p)
    


    NOTE: the old version of the answer below refers to the bokeh.charts API, which was since deprecated and removed

    As of recent Bokeh releases (e.g. 0.12.4 or newer), this is now much simpler to accomplish using FuncTickFormatter:

    import pandas as pd
    from bokeh.charts import Bar, output_file, show
    from bokeh.models import FuncTickFormatter
    
    skills_list = ['cheese making', 'squanching', 'leaving harsh criticisms']
    pct_counts = [25, 40, 1]
    df = pd.DataFrame({'skill':skills_list, 'pct jobs with skill':pct_counts})
    p = Bar(df, 'index', values='pct jobs with skill', title="Top skills for ___ jobs", legend=False)
    label_dict = {}
    for i, s in enumerate(skills_list):
        label_dict[i] = s
    
    p.xaxis.formatter = FuncTickFormatter(code="""
        var labels = %s;
        return labels[tick];
    """ % label_dict)
    
    output_file("bar.html")
    show(p)
    

提交回复
热议问题