简体   繁体   中英

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 ). The labels are being populated with values from a column called returns in the df, which is of float datatype. Some of the labels are showing up with very many decimal places (0.130000000007).
How can I limit the values being displayed in the heatmap cells labels to show only 2 decimal places?
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) ? Or if you just want to cut off the rest 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. To fix this you need to coerce the Pandas column as below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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