Search code examples
pythondata-visualizationbokeh

All data being remove from bokeh plot using click_policy="hide"


I'm trying to do an interactive plot with bokeh to visualize t-SNE data in a 2D chart. It should display 9 clothes categories. See my code and variables below.

df:

             x         y       labels   colors                             imgs
0     0.017387 -0.270469  T-shirt/top  #1f77b4     ./fashion_mnist_images/0.png
1    -0.306095 -0.099984      Trouser  #ff7f0e     ./fashion_mnist_images/1.png
2     0.066467  0.020477     Pullover  #2ca02c     ./fashion_mnist_images/2.png
3     0.170224  0.000206     Pullover  #2ca02c     ./fashion_mnist_images/3.png
4    -0.029488 -0.157343        Dress  #d62728     ./fashion_mnist_images/4.png
       ...       ...          ...      ...                              ...
9995 -0.024929 -0.099063  T-shirt/top  #1f77b4  ./fashion_mnist_images/9995.png
9996  0.044125 -0.013741        Shirt  #e377c2  ./fashion_mnist_images/9996.png
9997  0.101816  0.103228          Bag  #bcbd22  ./fashion_mnist_images/9997.png
9998  0.260997  0.035555          Bag  #bcbd22  ./fashion_mnist_images/9998.png
9999  0.106888 -0.178166      Trouser  #ff7f0e  ./fashion_mnist_images/9999.png
[10000 rows x 5 columns]

code:

def plot_tsne_data(title):
    source = ColumnDataSource(
        data = dict(
                x = df['x'].values,
                y = df['y'].values,
                img = df['imgs'].values,
                label = df['labels'].values,
                color = df['colors'].values
            )
        )
    hover = HoverTool(
            tooltips="""
            <div>
                <img src="@img" height="28" alt="@img" width="28"></img>
            </div>
            """
        )
    tools = [hover, "pan", "wheel_zoom", "box_zoom", "reset"]
    plot = figure(plot_width=784, plot_height=600, title=title, tools=tools, toolbar_location="below")
    plot.circle("x", "y", size=3, color='color', legend_group='label', source=source)
    plot.add_layout(plot.legend[0], 'right')
    plot.legend.click_policy="hide"
    return plot
        
fig = plot_tsne_data("Fashion MNIST - t-SNE")
show(fig)

Output plot: enter image description here

Everything seems to be fine with the plot, except when I try to click in any legend. When an user click in one item of the legend, like "Trouser", it should delete only Trouser, but it's removing all data. I would be grateful if someone could help.

Example image:enter image description here


Solution

  • Unfortunately legend hiding/muting is not compatible with automatically grouped legends. You will need to have a separate call to circle for each group (with a legend_label instead), in order for them to be individually hide-able.