[파이썬] bokeh 그래프 애니메이션

In this blog post, we will explore how to create animated graphs using the Bokeh library in Python. Bokeh is a powerful data visualization library that provides a wide range of interactive and dynamic plotting options.

What is Bokeh?

Bokeh is an open-source data visualization library in Python that targets modern web browsers for presentation. It allows you to create interactive plots, dashboards, and data applications in the browser.

Getting Started with Bokeh

Before we start creating animated graphs, let’s make sure we have Bokeh installed. You can install Bokeh using pip:

pip install bokeh

Once installed, we can import the necessary modules and begin creating our animated graph.

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.models import FuncAnimation
from bokeh.io import output_notebook

Creating an Animated Graph

To create an animated graph in Bokeh, we first need to create a figure. We can set up the figure with appropriate parameters such as x-axis and y-axis ranges, labels, and titles.

output_notebook()

p = figure(x_range=(0, 10), y_range=(0, 10))
p.xaxis.axis_label = 'X-axis'
p.yaxis.axis_label = 'Y-axis'
p.title.text = 'Animated Graph'

Next, we need to define the data source for our graph. In this example, let’s use a simple sine wave function.

def sine_wave(x):
    return 5 * sin(x)

x_vals = linspace(0, 10, 100)
y_vals = sine_wave(x_vals)

source = ColumnDataSource(data={'x': x_vals, 'y': y_vals})

Now, let’s create the line glyph for our graph.

line = p.line(x='x', y='y', source=source)

Finally, we can define an update function that will be called for each frame of the animation. This function will update the y-values of the graph using the sine wave function.

def update(frame):
    y_new = sine_wave(x_vals + frame / 10)
    source.data = {'x': x_vals, 'y': y_new}

Lastly, we can use the FuncAnimation class to animate our graph by repeatedly calling the update function.

animation = FuncAnimation(p, update, frames=range(100), repeat=True)
show(p)

Conclusion

Bokeh provides a straightforward way to create animated graphs in Python. With its interactive capabilities and extensive customization options, Bokeh is a powerful tool for displaying dynamic data visualizations.

In this blog post, we learned how to create an animated graph using Bokeh. We explored the necessary steps, from setting up the figure to defining the data source and updating the graph with an animation function.

Remember to experiment with different data sources and animation functions to create unique and engaging visualizations. Bokeh’s documentation provides a wealth of resources and examples to help you explore its full potential.

Happy coding and happy visualizing!