[파이썬] bokeh 마우스 및 터치 이벤트 처리

Bokeh is a powerful data visualization library in Python that allows you to create interactive and visually appealing plots. In addition to its extensive functionality for creating static plots, Bokeh also provides support for handling mouse and touch events, allowing users to interact with the plot in real-time.

In this blog post, we will explore how to handle mouse and touch events in Bokeh using Python. We will cover basic event handling and demonstrate how to incorporate these events into your Bokeh applications.

Detecting mouse events

To handle mouse events in Bokeh, you can use the TapTool, HoverTool, or BoxZoomTool classes, among others. These tools allow you to respond to specific mouse events, such as clicking, hovering, or zooming.

Here’s an example of how to detect a mouse click event using the TapTool:

from bokeh.plotting import figure, show
from bokeh.models import TapTool

# Create a plot
p = figure()

# Add a glyph or scatter plot to the plot
p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5])

# Create a TapTool instance
tap_tool = TapTool()

# Attach a callback function to the 'tap' event
tap_tool.callback = CustomCallback()

# Add the tap tool to the plot
p.add_tools(tap_tool)

# Show the plot
show(p)

In the code above, we create a TapTool instance and attach a custom callback CustomCallback() to the ‘tap’ event. The callback function will be called whenever a mouse click event occurs on the plot.

Handling touch events

Bokeh also provides support for handling touch events on touch-enabled devices. You can use the TapTool or HoverTool classes to detect touch events such as tapping or hovering.

Here’s an example of how to handle touch events using the TapTool:

from bokeh.plotting import figure, show
from bokeh.models import TapTool, OpenURL

# Create a plot
p = figure()

# Add a glyph or scatter plot to the plot
p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5])

# Create a TapTool instance
tap_tool = TapTool(behavior="select", callback=OpenURL(url="http://example.com"))

# Add the tap tool to the plot
p.add_tools(tap_tool)

# Show the plot
show(p)

In this example, we create a TapTool instance with behavior="select" to enable touch selection. We also attach an OpenURL callback to open a specified URL when the user touches the plot.

Conclusion

Handling mouse and touch events in Bokeh allows you to create highly interactive and engaging data visualizations. Whether you want to respond to mouse clicks or touch gestures, Bokeh provides easy-to-use tools to incorporate event handling into your Python applications.

In this blog post, we covered the basics of handling mouse and touch events in Bokeh using the TapTool. You can explore other tools and their event handling capabilities in the Bokeh documentation.

Happy event handling with Bokeh!