如何将字典浮点值转为百分比并格式化matplotlib标题?
Solution for Dictionary Formatting to Matplotlib Title
Step 1: Convert Float Values to Percentage Strings
First, process each float value in the dictionary to a percentage string with two decimal places. Use a dictionary comprehension for this:
d = {"{ModelA}": 0.9567, "{ModelB}": 0.8923} formatted_values = {k: f"{v*100:.2f}%" for k, v in d.items()}
Step 2: Clean Up Dictionary Keys
Remove quotes and curly braces from the keys using string stripping methods:
cleaned_dict = {key.strip('"{}'): value for key, value in formatted_values.items()}
You can also combine both steps into one line for efficiency:
cleaned_dict = {k.strip('"{}'): f"{v*100:.2f}%" for k, v in d.items()}
Step 3: Format into Matplotlib Title String
Convert the cleaned dictionary into a readable title format. For example, to get a title like Accuracy: ModelA=95.67%, ModelB=89.23%, use:
title_str = "Accuracy: " + ", ".join([f"{k}={v}" for k, v in cleaned_dict.items()])
Then apply it to your matplotlib chart:
import matplotlib.pyplot as plt plt.title(title_str) plt.show()
Example Result
Original dictionary:
{"{ModelA}": 0.9567, "{ModelB}": 0.8923}
Generated title: Accuracy: ModelA=95.67%, ModelB=89.23%
内容的提问来源于stack exchange,提问作者ah bon
相关产品推荐
相关产品推荐

