如何将dict生成的JSON数据高效绘制为饼图与柱状图?
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

