To plot a pie chart using the Bokeh library in Python, follow these steps:
- Install the Bokeh library if you haven’t already:
pip install bokeh
- Import the necessary modules from Bokeh:
from bokeh.plotting import figure, show from bokeh.io import output_file from bokeh.transform import factor_cmap import pandas as pd
- Prepare your data. For this example, we’ll use a simple dictionary:
data = {'A': 20, 'B': 15, 'C': 30, 'D': 35}
- Convert the data into a format suitable for Bokeh:
data_df = pd.DataFrame(list(data.items()), columns=['Category', 'Value'])
- Set up the output file and plot the pie chart:
# Set up the output file output_file('pie_chart.html') # Create a pie chart p = figure(height=350, title="Pie Chart", toolbar_location=None, tools="hover", tooltips="@Category: @Value", x_range=(-0.5, 1.0)) # Add a wedge renderer p.wedge(x=0, y=1, radius=0.4, start_angle='start_angle', end_angle='end_angle', line_color='white', fill_color='color', legend_field='Category', source=data_df) # Show the plot show(p)
This code creates a pie chart and saves it as ‘pie_chart.html’. You can open this file in a web browser to view the chart.