简体   繁体   English

显示散景标签值精确到小数点后两位(浮点精度误差)

[英]Display Bokeh labels values correct to 2 decimal places (floating point precision error)

I am creating a heatmap using Bokeh with the datasource being a Pandas dataframe ( monthly_rets ).我正在使用 Bokeh 创建一个热图,数据源是 Pandas 数据框( monthly_rets )。 The labels are being populated with values from a column called returns in the df, which is of float datatype.标签被填充值从一个称为列returns在DF,这是float数据类型的。 Some of the labels are showing up with very many decimal places (0.130000000007).一些标签显示有非常多的小数位 (0.130000000007)。
How can I limit the values being displayed in the heatmap cells labels to show only 2 decimal places?如何将热图单元格标签中显示的值限制为仅显示 2 个小数位?
My current code is as below:我目前的代码如下:

source = ColumnDataSource(monthly_rets)
plot = figure(title="Monthly Returns (%)",
                x_range=months, y_range=years,
                plot_height=300, plot_width=800)
plot.rect(x="rtn_month", y="rtn_year", width=1, height=1,
            source=monthly_rets,
            fill_color={'field': 'returns', 'transform': mapper},
            name="returns")
labels = LabelSet(x="rtn_month", y="rtn_year", text="returns",
                    text_font_size="10pt", source=source, 
                   text_align='center')
plot.add_layout(labels)

I am not sure exactly, but try round(source,2) ?我不确定,但试试round(source,2) Or if you just want to cut off the rest source = int(source * 100) / 100或者,如果你只是想切断其余的source = int(source * 100) / 100

Turns out Bokeh requires a string to be displayed and all string manipulation needs to happen before its handed to the Bokeh Datasource.事实证明 Bokeh 需要显示一个字符串,并且所有字符串操作都需要在将其传递给 Bokeh 数据源之前进行。 To fix this you need to coerce the Pandas column as below:要解决此问题,您需要按如下方式强制 Pandas 列:

monthly_rets['returns'] = monthly_rets['returns'].astype(str)
monthly_rets['returns'] = monthly_rets['returns'].str.slice(0,5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM