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

如何将Matplotlib折线柱状图的数据标签设置为百分比格式?

解决Matplotlib折线柱状组合图数据标签百分比格式问题

要将数据标签从小数改为带两位小数的百分比格式,只需修改添加标签的循环代码,把原始小数数值格式化为百分比字符串即可:

修改后的完整代码

import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
plt.figure(figsize=(9, 6), dpi=100)
x = ['>12 Months','6-12 Months','3-6 Months','1-3 Months','1-4 Weeks','>1 Times Per Week']
y = [0.0964,0.1607,0.4158,0.3054,0.0215,0.0001]
z = [11544,19247,49794,36572,2578,16]
plt.bar(x=x, height=z, label='Vehicles Num', color='Blue', alpha=0.7, width=0.5)
plt.legend(loc="upper left")
plt.title("Frequency Distribution of Hood Ajar/Closed Events",size=15)
plt.xlabel("Frequency",size=13)
plt.ylabel("Number of Vehicles",size=13)
ax2 = plt.twinx()
ax2.set_ylabel("Percentage",size=13)
ax2.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))
plt.plot(x, y, "r", marker='.', c='r', ms=8, linewidth='1', label="Percentage")
plt.legend(loc="upper right")
# 关键修改:将小数格式化为两位小数的百分比字符串
for a, b in zip(x, y):
    plt.text(a, b, f"{b*100:.2f}%", ha='center',va='bottom',fontsize=13)
plt.show()

核心修改说明

  • 在循环添加数据标签时,使用f"{b*100:.2f}%"将原始小数(如0.0964)转换为9.64%格式的字符串:
    • b*100:将小数转换为百分比数值
    • :.2f:保留两位小数
    • %:添加百分比符号

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:50:26