在散景中的 NumeralTickFormatter 中使用 € 作为货币符号

问题描述

我想使用 € 符号而不是 $ 来格式化由 Holoviews (hv.Bars) 创建的散景图中的数字。

formatter = NumeralTickFormatter(format=f"{€ 0.00 a)")

不幸的是,这只会产生一个格式化的数字,而不是欧元符号

此外,这里提到的解决方法

How to format bokeh xaxis ticks with currency

formatter = PrintfTickFormatter(format=f'€ 0.00 a') 

不起作用。

我实际上认为散景应该适应这一点,并提供添加任何符号的可能性。

解决方法

这可以使用 FuncTickFormatter 和一些 TypeScript 代码来完成。

from bokeh.models import FuncTickFormatter
p.xaxis.formatter = FuncTickFormatter(code='''Edit some typescript here.''')

最小示例 如果您的目标是为 0 到 1e7 之间的值编辑 x 轴,这应该可行。这将不为小于 1000 的值选择任何单位,为 1000 和 1e6 之间的值选择 k,为更大的值选择 m

from bokeh.plotting import figure,output_notebook,show
from bokeh.models import FuncTickFormatter
output_notebook()

# create a new plot with the toolbar below
p = figure(plot_width=400,plot_height=400,title=None,toolbar_location="below")
x = [xx*1e6 for xx in range(1,6)]
y = [2,5,8,2,7]
p.circle(x,y,size=10)
p.xaxis.formatter = FuncTickFormatter(code='''
                                            if (tick < 1e3){
                                                var unit = ''
                                                var num =  (tick).toFixed(2)
                                              }
                                              else if (tick < 1e6){
                                                var unit = 'k'
                                                var num =  (tick/1e3).toFixed(2)
                                              }
                                              else{
                                                var unit = 'm'
                                                var num =  (tick/1e6).toFixed(2)
                                                }
                                            return `€ ${num} ${unit}`
                                           '''
                                           )

show(p)

输出

using FuncTickFormatter

,

NumeralTickFormatterPrintfTickFormatter 是不同的,它们使用完全不同的格式字符串。如果你想使用PrintfTickFormatter,你需要给它一个有效的“printf”格式字符串:

PrintfTickFormatter(format='€ %0.2f')

enter image description here

有效的 printf 格式都被描述了 in the documentation