You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 used Donut (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_json is more reliable than Bokeh's df_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.charts module is deprecated—you'll need to use bokeh.plotting with wedge glyphs instead, but the above code works for older versions where bokeh.charts is available.

内容的提问来源于stack exchange,提问作者Nightwing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:17:04