Histogram Return Hovered Bin's Values

Screen Shot 2021-12-14 at 10.12.21 AM

Hi, I’m currently using D3 observable plot to implement this chart. I’m trying to implement this feature where if a bar on the histogram is hovered, the values inside that bin would be highlighted in another view. To do that, I would need to identify the values inside the hovered bin. Also, I’m not sure how to change the color of the bin when hovered. Does anyone know how do to that? Any help would be greatly appreciated!

Thank you!

Hi @ivansong3! I’m not sure from your post whether you’re trying to implement this with D3, or with Observable Plot. So the solution will depend on which library you’re using.

If you’re using D3:

You can use D3 to add an .on("mouseover", ...) event handler on the chart’s bars to update the bar’s color and capture the relevant data when a user hovers on a bar. Here’s an example forked from the D3 Histogram chart, see the comments in the InteractiveHistogram cell to understand the relevant changes: Interactive Histogram example / Anjana Vakil / Observable

In that example, we use an Observable view to capture the relevant data as the selectedData cell’s value, which we can then reference reactively in other cells e.g. the table cell that simply displays it in a table. Thanks to Observable’s reactivity, the data will update instantly as the user selects different bars.

If you’re using Plot:

To change the color of bars on hover, you can use the addTooltips function from @mkfreeman/plot-tooltip. Here’s an example: Plot Histogram tooltips example / Anjana Vakil / Observable

As for capturing the values inside the hovered bin for use in another cell, that’s more complicated, and currently not supported out of the box by Plot (though it’s on the roadmap!). If you’re really determined, you could hack together a solution using a view to capture the desired values and reactively update other cells. Here’s an example of using Plot for this type of interactivity: Interactive Plot Dashboard / Observable Ambassadors / Observable

Hope that helps!