首页 文章

如何在Bokeh中使用自定义标签作为刻度?

提问于
浏览
12

我理解你如何指定在Bokeh中显示的特定刻度,但我的问题是,是否有一种方法可以指定一个特定的标签来显示与位置 . 所以举个例子

plot.xaxis[0].ticker=FixedTicker(ticks=[0,1])

只会将x轴标签显示为0和1,但如果不显示0和1,我想显示Apple和Orange . 就像是

plot.xaxis[0].ticker=FixedTicker(ticks=[0,1], labels=['Apple', 'Orange'])

直方图不适用于我正在绘制的数据 . 反正在Bokeh中使用自定义标签吗?

2 回答

  • 15

    EDIT :更新了Bokeh 0.12.5 ,但在另一个答案中也看到了更简单的方法 .

    这对我有用:

    import pandas as pd
    from bokeh.charts import Bar, output_file, show
    from bokeh.models import TickFormatter
    from bokeh.core.properties import Dict, Int, String
    
    class FixedTickFormatter(TickFormatter):
        """
        Class used to allow custom axis tick labels on a bokeh chart
        Extends bokeh.model.formatters.TickFormatte
        """
    
        JS_CODE =  """
            import {Model} from "model"
            import * as p from "core/properties"
    
            export class FixedTickFormatter extends Model
              type: 'FixedTickFormatter'
              doFormat: (ticks) ->
                labels = @get("labels")
                return (labels[tick] ? "" for tick in ticks)
              @define {
                labels: [ p.Any ]
              }
        """
    
        labels = Dict(Int, String, help="""
        A mapping of integer ticks values to their labels.
        """)
    
        __implementation__ = JS_CODE
    
    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[0].formatter = FixedTickFormatter(labels=label_dict)
    output_file("bar.html")
    show(p)
    

    result of code

  • 3

    截至更近期的Bokeh版本( 0.12.14 左右),这甚至更简单 . 固定的刻度可以直接作为"ticker"值传递,并且可以提供主要的标签覆盖以明确地为特定值提供自定义标签:

    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)
    

    enter image description here


    注意:以下答案的旧版本是指 bokeh.charts API,该API已被弃用和删除

    截至最近的Bokeh版本(例如 0.12.4 或更新版本),现在使用 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)
    

相关问题