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

Matplotlib Pyplot调整Cost Ratio标注为指定科学计数法格式

调整Matplotlib中Cost Ratio数值的显示格式

问题说明

我有一张图表,蓝线上标注的是Cost Ratio(成本比率),当前用以下代码绘图:

fpr=[some values]
tpr=[some values]
CR = 
plt.plot(tpr,fpr)
plt.plot(x,y)
plt.plot(*intersection.xy, 'ro')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(["Cost Ratio"])
for x,y,z in zip(tpr,fpr,CR):
    label = "{:.2f}".format(z) 
    plt.annotate(label, # 标注文本
                 (x,y),annotation_clip=True, # 标注坐标
                 textcoords="offset points", # 文本定位方式
                 xytext=(0,10), # 文本与点的偏移距离
                 ha='center') # 水平居中对齐

plt.show()

当前Cost Ratio的数值为:

[3.436400227231698e-11
6.872800454463395e-11
1.374560090892679e-10
2.749120181785358e-10
5.498240363570716e-10
1.0996480727141433e-09
2.1992961454282866e-09
4.398592290856573e-09
8.797184581713146e-09
1.7594369163426292e-08
37.7836200753334]

我需要把这些数值显示为如下格式:

[3.4e-11
6.8e-11
1.3e-10
2.7e-10
5.4e-10
1.0e-09
2.1e-09
4.3e-09
8.7e-09
1.7e-08
37.7]

解决方法

通过自定义数值格式化逻辑,区分极小值和常规数值的显示方式,修改代码中的标注部分即可:

for x,y,z in zip(tpr,fpr,CR):
    # 对极小值用科学计数法保留1位小数,常规值保留1位小数
    if z < 1e-6:
        label = "{:.1e}".format(z)
    else:
        label = "{:.1f}".format(z)
    plt.annotate(label, 
                 (x,y), annotation_clip=True,
                 textcoords="offset points",
                 xytext=(0,10),
                 ha='center')

细节说明

  • 阈值1e-6可根据需求调整,用于区分需要用科学计数法的极小值
  • {:.1e}会自动将极小值格式化为保留1位小数的科学计数法,比如3.436e-11转为3.4e-11
  • {:.1f}会将常规数值保留1位小数,比如37.783转为37.7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:10:20