我理解你如何指定在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中使用自定义标签吗?
答案 0 :(得分:19)
截至更近期的Bokeh版本(bokeh.charts
左右),这甚至更简单。固定的刻度可以直接作为“股票”值传递,并且可以提供主要的标签覆盖以明确提供特定值的自定义标签:
0.12.4
{{3}}
注意:以下答案的旧版本是指FuncTickFormatter
API,该API已弃用并已删除
截至最近的Bokeh版本(例如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)
或更新版本),现在使用{{1}}更容易实现:
{{1}}
答案 1 :(得分:4)
编辑:针对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)