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

如何将dict生成的JSON数据高效绘制为饼图与柱状图?

Optimizing JSON Key-Value Pair Visualization for Pie Charts

Great question! Your current approach of directly working with the loaded dictionary is already a strong solution, but let's explore a few refinements and alternatives to make your workflow even cleaner, depending on your needs.

Your Existing Dictionary-Based Method (Optimized)

Your second code snippet is lightweight and perfectly suited for your simple key-value JSON structure—no need to introduce pandas if you don't plan on additional data manipulation. Here's a polished version with common pie chart improvements:

from matplotlib import pyplot as plt
import json

# Load the JSON data as a dictionary
with open('path/to/your/file.json') as f:
    expense_data = json.load(f)

# Extract labels and values directly from the dictionary
categories = list(expense_data.keys())
amounts = list(expense_data.values())

# Create the pie chart with helpful formatting
fig, ax = plt.subplots()
# Add percentage labels, adjust text size, and format wedges
wedges, texts, autotexts = ax.pie(
    amounts,
    labels=categories,
    autopct='%1.1f%%',  # Show percentages to one decimal place
    textprops={'fontsize': 10},
    wedgeprops={'linewidth': 1, 'edgecolor': 'white'}  # Add clear separators between slices
)
# Ensure the pie chart stays circular
ax.axis('equal')
# Add a descriptive title
ax.set_title('Monthly Expense Distribution')

plt.show()

Fixing the Pandas DataFrame Approach

The reason you needed subplots=True in your first attempt is because you loaded the JSON into a single-row DataFrame—each category was a column, and pandas tried to plot every column as a separate pie chart. Instead, reshape the data into a two-column DataFrame (categories and amounts) to plot a single pie chart without subplots:

from matplotlib import pyplot as plt
import pandas as pd
import json

with open('path/to/your/file.json') as f:
    expense_data = json.load(f)

# Convert the dictionary to a structured DataFrame
df = pd.DataFrame(
    list(expense_data.items()),
    columns=['Category', 'Amount']
)

# Plot a single pie chart using the "Amount" column
df.plot.pie(
    y='Amount',
    labels=df['Category'],
    autopct='%1.1f%%',
    textprops={'fontsize': 10}
)
plt.axis('equal')
plt.title('Monthly Expense Distribution')
plt.show()

This approach is useful if you want to perform additional data operations (like sorting categories by amount, filtering small values, or merging with other datasets) before plotting—pandas excels at these tasks.

When to Choose Which Method?

  • Use the dictionary-based approach for quick, lightweight plotting when you don't need to manipulate the data beyond extracting labels and values.
  • Use the pandas approach if you plan to clean, transform, or analyze the data before visualizing it (e.g., sorting expenses from highest to lowest, excluding categories below a threshold).

Both methods are valid—pick the one that aligns with your overall workflow!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:53:16