[파이썬] bokeh 날짜 및 시간 데이터 처리

Bokeh is a powerful data visualization library in Python that can be used to create interactive and visually appealing plots. One aspect of data that is commonly encountered and needs to be handled in visualization is date and time data. In this blog post, we will explore how to handle date and time data in Bokeh.

1. Importing the necessary libraries

To get started with Bokeh, we need to import the necessary libraries. In addition to Bokeh, we will also use the Pandas library for data manipulation.

import pandas as pd
from bokeh.plotting import figure, show
from bokeh.io import output_notebook

2. Loading the data

Next, we need to load the data containing the date and time information. For this example, let’s assume we have a CSV file with two columns: ‘datetime’ and ‘value’. The ‘datetime’ column contains the date and time values, and the ‘value’ column contains the corresponding data value.

data = pd.read_csv('data.csv', parse_dates=['datetime'])

Here, we use the parse_dates argument in the read_csv function to ensure that the ‘datetime’ column is parsed as a date and time object.

3. Creating a Bokeh figure

Now, we can create a Bokeh figure to visualize the data. We will use the figure function to create the figure object.

p = figure(x_axis_type="datetime", plot_width=800, plot_height=400)

Here, we set the x_axis_type argument to “datetime” to inform Bokeh that the x-axis represents date and time values.

4. Adding data to the figure

Next, we add the data to the figure using the appropriate data source. Bokeh supports multiple data source types, but for this example, we will use the ColumnDataSource class.

source = ColumnDataSource(data=dict(datetime=data['datetime'], value=data['value']))
p.line(x='datetime', y='value', line_color='blue', source=source)

Here, we create a ColumnDataSource object and pass it along with the column names to the data argument. We then use the ‘datetime’ and ‘value’ columns as the x and y values, respectively, when plotting the line.

5. Displaying the plot

Finally, we display the plot using the show function.

output_notebook()
show(p)

The output_notebook function allows the plot to be displayed inline in a Jupyter notebook. Alternatively, you can use output_file function to save the plot to a file.

Conclusion

In this blog post, we explored how to handle date and time data in Bokeh for data visualization. By following the steps mentioned, you can create interactive plots with date and time axes using Bokeh. Bokeh provides several additional customization options for date and time axes, such as formatting and tick intervals, which you can further explore in the official Bokeh documentation.

Happy coding with Bokeh!