I want to display a scatter plot with a couple million points in my Streamlit app and found that Datashader can produce produce such a plot very quickly and that Streamlit can display the resulting image - but only the image, with no axes around. What is the easiest way of doing this?
What I have found so far: with dataframe df with time-index and columns temp and voc, this code displays the heatmap as a 800x600 bitmap (with no decorations):
import datashader as ds
import colorcet # color maps, comes with datashader
cvs = ds.Canvas(plot_width=800, plot_height=600)
agg = cvs.points(df, 'temp', 'voc')
img = ds.tf.shade(agg, cmap=colorcet.fire)
img
This works because img is an xarray.DataArray of RGB values for each pixel. (DataArray provides “a wrapper around numpy ndarrays that uses labeled dimensions and coordinates to support metadata aware operations”).
(Similarly, agg is a DataArray of counts for every grid point/pixel)
Then I could use this approach to create bokeh plots and display them in Streamlit. The problem here is the resolution: my generated image is 800x600, but for Bokeh one specifies dimensions of the whole plot, including decorations and legends, so I did not found a way to ensure that Bokeh displays the image at exactly 100% zoom.
The page width does not matter here.
The issue is that datashader creates a bitmap, in my example 800x600.
Bokeh can include a bitmap in its chart, but the problem is that it gets resampled to fit the specified chart size - and since the chart size in Bokeh refers to the whole chart (including axes descriptions and legends), I did not find a way to specify the dimensions such that the included image would be exactly 800x600 (and therefore avoid rescaling)…
The Datashader docs recommend using HoloViews for this purpose, because HoloViews is set up to configure Bokeh callbacks that read the size of the plot area (via the HoloViews RangeXY Stream) and re-render the Datashader plot to fit the plot area. Doing this requires two-way communication between JS and Python, which is available from Panel but I’m not sure Streamlit supports. In the absence of the bidirectional comms, you could use HoloViews Matplotlib support to render the plot at a dpi e.g. twice the screen resolution and twice the line thickness so that when displayed it has axes and enough resolution to look good when displayed. I think the Matplotlib backend might actually be able to specify the exact size of the rendered image with axes (unlike in Bokeh), in which case you don’t need to use a higher resolution.