我了解如何指定在 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
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)
这可以作为分类数据处理,请参阅 bokeh 文档。
from bokeh.plotting import figure, show
categories = ['A', 'B','C' ]
p = figure(x_range=categories)
p.circle(x=categories, y=[4, 6, 5], size=20)
show(p)
x 刻度的标签如果不落在 10 的倍数上,则不会 可见。
肮脏的黑客是使用填充来以 10 的倍数扩展刻度标签,如图所示 -
label_dict = { 0: "g (1-7)", 1: "", 2: "", 3: "", 4: "", 5: "", 6: "", 7: "", 8: "", 9: "", 10: "O (8-13)", 11: "", 12: "", 13: "", 14: "", 15: "", 16: "", 17: "", 18: "", 19: "", 20: "E (14-18) I (19-24)", 21: "", 22: "", 23: "", 24: "", 25: "", 26: "", 27: "", 28: "", 29: "", 30: "C (25-35) ", 31: "", 32: "", 33: "", 34: "", 35: "", 36: "", 37: "", 38: "", 39: "", 40: "λ(36) k(37) A / L (38-40)", 41: "", 42: "", 43: "", 44: "", 45: "", 46: "", 47: "", 48: "", 49: ""}