Search code examples
pythonpandasbokehprecision

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)

Solution

  • 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)