You need to enable JavaScript to run this app. 如何修改Matplotlib横向柱状图x轴刻度标签的显示单位为百万级
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Matplotlib横向柱状图x轴刻度标签的显示单位为百万级

解决方案

你可以通过以下两种方式实现x轴刻度以百万为单位显示:

方式1:直接转换绘图数据单位(最简便)

将原始营收数据统一除以10^6后再绘图,刻度会自动匹配百万单位,修改后的完整代码如下:

import numpy as np
import pandas as pd
import matplotlib.ticker as plticker
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import display
from pandas import Series

%matplotlib inline

# Define Figure Size
fig, ax = plt.subplots(figsize=(25,25))

# Get the average revenue for each release year, convert to million unit
average_revenue = df2.groupby('release_year')['revenue_adj'].mean() / 1000000

# Find positions of y ticks
y_pos = np.arange(len(df2['release_year'].unique()))
# Set up Bar Chart
ax.set_yticks(y_pos)
ax.set_yticklabels(sorted(df2['release_year'].unique()))
ax.set_xlabel('Revenue in Millions', fontsize=16)
ax.set_ylabel('Release Year', fontsize=16)
ax.set_title('Revenue by Release Year', fontsize=20)

# Set Size of X and Y labels
plt.rc('xtick', labelsize=14)
plt.rc('ytick', labelsize=14)

# Put Values next to Each Bar
for i, v in enumerate(average_revenue):
    ax.text(v, i, ('$' + str(round(v,2)) + 'M'), color='blue')
    
ax.invert_yaxis()  # labels read top-to-bottom

# Draw Bar Chart
ax.barh(y_pos, average_revenue, align='center', color='green', ecolor='black')

方式2:仅修改刻度显示规则(不改动原始数据)

如果需要保留原始数据绘图,仅调整刻度的显示数值,可以使用matplotlib.ticker.FuncFormatter自定义刻度格式化逻辑,在你现有代码的基础上添加如下代码即可:

from matplotlib.ticker import FuncFormatter

# 自定义x轴刻度格式化函数,将原始数值(元)转换为百万单位显示
def million_formatter(x, pos):
    return f"{x/1000000:.1f}"

# 应用格式化规则到x轴
ax.xaxis.set_major_formatter(FuncFormatter(million_formatter))

把这段代码加在ax.barh()之前的任意位置即可生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 01:30:05