如何在Bokeh中使用自定义标签作为刻度线? [英] How do I use custom labels for ticks in Bokeh?

查看:389
本文介绍了如何在Bokeh中使用自定义标签作为刻度线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

将仅在0和1处显示x轴标签,但是如果我不想显示0和1,我想显示Apple和Orange,该怎么办.像

will only show the x-axis labels at 0 and 1, but what if instead of showing 0 and 1 I wanted to show Apple and Orange. Something like

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

直方图不适用于我正在绘制的数据.无论如何,这样在Bokeh中可以使用自定义标签吗?

A histogram won't work for the data I am plotting. Is there anyway to use custom labels in Bokeh like this?

推荐答案

从Bokeh的最新版本(0.12.14左右)开始,这甚至更加简单.固定刻度线可以直接作为"ticker"值传递,并且可以提供主要标签替代来显式提供特定值的自定义标签:

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)

注意:以下答案的旧版本指的是bokeh.charts API,此API自不推荐使用并已删除

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

从Bokeh的最新版本(例如0.12.4或更高版本)开始,现在使用FuncTickFormatter来完成此操作要简单得多:

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)

这篇关于如何在Bokeh中使用自定义标签作为刻度线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆