【问题标题】:How do I use custom labels for ticks in Bokeh?如何在 Bokeh 中为刻度使用自定义标签?
【发布时间】:2016-09-07 11:31:21
【问题描述】:

我了解您如何指定要在 Bokeh 中显示的特定刻度,但我的问题是是否有一种方法可以分配特定标签以显示与位置。比如

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

只会在 0 和 1 处显示 x 轴标签,但是如果我不想显示 0 和 1 我想显示 Apple 和 Orange 怎么办。类似的东西

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

直方图不适用于我正在绘制的数据。有没有像这样在 Bokeh 中使用自定义标签?

【问题讨论】:

    标签: bokeh


    【解决方案1】:

    对于 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)
    


    注意:以下答案的旧版本指的是 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)
    

    【讨论】:

    • 看起来很有用,但它只是在我的浏览器中给了我一个空白页。
    • 使用 Bokeh 0.12.40.12.5 为我工作,因此需要更多信息来调查原因。
    • 我在 0.12.2,升级已修复它:-)
    【解决方案2】:

    编辑:针对 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)
    

    【讨论】:

    • skills list and pct_counts were created, but not shown here
    • 哈,这就是你投反对票的原因?您本可以编辑编码并具有建设性。
    • 我会,但还是不行。生成的JS找不到FixedTickFormatter
    • 对我来说很好。 Ubuntu 16.04 上的 Python2,散景为 0.12.3。添加图片。
    • 在 Ubuntu 14.04 和散景 0.12.3 上。逐字使用您的代码后出现此错误:ValueError: expected an element of either Column(Float) or Column(String), got array([25], dtype=int64)
    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 2016-04-27
    • 2012-05-08
    • 2014-04-10
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2016-10-27
    相关资源
    最近更新 更多