You need to enable JavaScript to run this app. Matplotlib中如何设置Y轴显示百万级数值而非科学计数法?
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib中如何设置Y轴显示百万级数值而非科学计数法?

Matplotlib Y轴去除科学计数法、显示指定单位数值的实现方法

核心逻辑

Matplotlib默认对量级超过阈值的大数值轴自动启用科学计数法展示,可通过自定义刻度格式化器覆盖默认规则,实现中文单位的展示需求。

操作步骤

  • 补充导入所需的刻度格式化模块,在原有导入代码中添加:
    from matplotlib.ticker import FuncFormatter

  • 选择适配的刻度格式化规则:
    方案A(推荐):转为中文「万」单位展示
    该方案会将原始数值折算为万为单位,1.75×10^7的原始值会直接显示为1750万,完全匹配需求。
    首先定义格式化函数:

    def format_y_axis(x, pos):
        # :.0f 表示无小数位,可根据需求调整为:.1f等格式
        return f"{x / 10000:.0f}万"
    

    之后在创建完ax对象后,绑定规则到Y轴:
    ax.yaxis.set_major_formatter(FuncFormatter(format_y_axis))

    方案B:关闭科学计数法,显示完整原始数值
    如果不需要附加中文单位,仅要去掉1e7类的科学计数法后缀、显示完整数字(如17500000),可直接添加以下代码:
    ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: f"{int(x)}"))

完整可运行代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pingouin as pg
import plotly
import plotly.express as px
from matplotlib.ticker import FuncFormatter

data = pd.read_csv('COVID19_state.csv')

fig, ax = plt.subplots(figsize=(12,5))
ax = sns.barplot(x = 'State', y = 'Tested', data = data, color='blue');
ax.set_title('Tested by State')
ax.set_xticklabels(labels=data['State'], rotation=90)
ax.set_ylabel('Tested')
ax.set_xlabel('State')

# 以方案A为例,可替换为方案B的代码
def format_y_axis(x, pos):
    return f"{x / 10000:.0f}万"
ax.yaxis.set_major_formatter(FuncFormatter(format_y_axis))

plt.grid()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 16:24:02