如何使用Bokeh读取JSON文件并基于Pandas DataFrame创建环形饼图
Fixing Your Bokeh Donut Chart from JSON Data
Let's walk through the corrections and improvements to get your donut chart working properly:
Key Issues in Your Original Code
- Typo: You imported
donut(lowercase) but usedDonut(capitalized) when creating the chart. - Missing Value Column: Your JSON data only has categorical fields (
name,task), but the donut chart requires numerical values (like counts of each task/person pair). - Data Reading: Using Pandas' built-in
read_jsonis more reliable than Bokeh'sdf_from_json.
Corrected Step-by-Step Code
1. Import Required Libraries
First, fix the import for Donut (match the capitalization):
from bokeh.charts import Donut, show, output_file import pandas as pd
2. Read JSON Data into Pandas DataFrame
Use Pandas to load your JSON file:
# Replace with your actual file path df = pd.read_json('path/to/your/data.json')
3. Aggregate Data to Get Counts
Since your JSON doesn't include numerical values, we need to count how many times each (name, task) pair appears:
# Group by name and task, then calculate counts df_counts = df.groupby(['name', 'task']).size().reset_index(name='count')
4. Create the Donut Chart
Now use the aggregated counts to build your nested donut (outer ring = names, inner ring = tasks):
# Initialize donut chart with correct parameters d = Donut( df_counts, label=['name', 'task'], # Nested labels for outer/inner rings values='count', # Use our calculated count values text_font_size='8pt' )
5. Output and Display the Chart
output_file("donut.html") show(d)
Example Output Explanation
If your JSON data looks like this:
[ {"name": "Anand", "task": "development"}, {"name": "Anand", "task": "testing"}, {"name": "Priya", "task": "development"}, {"name": "Priya", "task": "design"}, {"name": "Priya", "task": "testing"} ]
The resulting donut will:
- Have outer segments for Anand (2 tasks) and Priya (3 tasks)
- Split each outer segment into inner segments for their specific tasks (e.g., Anand's segment splits into development and testing, each with count 1)
Notes
- Ensure your file path is correct (use absolute path if relative paths aren't working)
- If you're using a newer version of Bokeh (post-0.13), the
bokeh.chartsmodule is deprecated—you'll need to usebokeh.plottingwith wedge glyphs instead, but the above code works for older versions wherebokeh.chartsis available.
内容的提问来源于stack exchange,提问作者Nightwing
相关产品推荐
相关产品推荐

