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

如何在Python Matplotlib柱状图中去除指数值并设置指定Y轴刻度

解决Matplotlib对数Y轴指数显示问题

你的问题出在使用对数刻度后,普通的ticklabel_format设置无法覆盖对数轴的默认格式化逻辑。以下是修改后的代码,能让Y轴显示0.1、1、10、100、1000这些普通数值:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

# 设置柱状图宽度
barWidth = 0.25
fig, ax = plt.subplots(figsize=(12, 8))  # 获取轴对象,方便后续精准设置
params = {'legend.fontsize': 20,
          'legend.handlelength': 2}
plt.rc('xtick', labelsize=20)
plt.rc('ytick', labelsize=20)
plt.rcParams.update(params)

# 各工具的耗时数据
dpkt_val = [0.06, 0.33, 0.58, 3.02, 7.01]
scapy_val = [0.59, 2.41, 5.85, 24, 56.15]
pyshark_val = [26.26, 152.94, 261.14, 1456.02, 0]

# 设置各柱状图的X轴位置
br1 = np.arange(len(dpkt_val))
br2 = [x + barWidth for x in br1]
br3 = [x + barWidth for x in br2]

# 绘制柱状图
plt.bar(br1, dpkt_val, color='r', width=barWidth,
        edgecolor='grey', label='dpkt', hatch='*')
plt.bar(br2, scapy_val, color='g', width=barWidth,
        edgecolor='grey', label='Scapy', hatch='//')
plt.bar(br3, pyshark_val, color='b', width=barWidth,
        edgecolor='grey', label='pyshark', hatch='-')

# 设置X轴标签与刻度
plt.xlabel('Filesize', fontweight='bold', fontsize=20)
plt.ylabel('Time(sec)', fontweight='bold', fontsize=20)
plt.xticks([r + barWidth for r in range(len(dpkt_val))],
           ['100MB', '500MB', '1GB', '5GB', '10GB'], fontsize=20)

# 核心设置:处理对数Y轴的刻度显示
plt.yscale('log')
# 手动指定需要显示的刻度值
plt.yticks([0.1, 1, 10, 100, 1000])
# 创建格式化器,关闭科学计数法与偏移量
formatter = ScalarFormatter()
formatter.set_scientific(False)
formatter.set_useOffset(False)
# 将格式化器绑定到Y轴
ax.yaxis.set_major_formatter(formatter)

plt.legend()
plt.show()

关键修改说明:

  • 改用fig, ax = plt.subplots()获取轴对象,方便直接操作Y轴的显示规则
  • 移除原代码中对对数轴无效的ticklabel_format调用
  • 手动指定yticks的显示值为你需要的0.1、1、10、100、1000
  • 使用ScalarFormatter强制关闭科学计数法,确保刻度以普通数字形式展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:35:29