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

如何将字典浮点值转为百分比并格式化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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:35:45