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

Matplotlib横向柱状图数值显示、排序及柱子缺失问题求助

解决横向柱状图的GDP数值显示与排序问题

问题背景

用matplotlib绘制各国GDP(BNP)横向柱状图时,原始代码会自动将百万、十亿、万亿级的大数值取整为1、2、3等小值,无法展示实际量级;自定义konverter函数转换格式后,又出现最低GDP的柱子消失、数据未排序的问题。

原始绘图代码:

import matplotlib.pyplot as plt

plt.barh(landStolpediagram, BNPStolpediagram)
plt.xlabel("BNP")
plt.ylabel("Land")
plt.title("Dine valgte land og deres BNP verdi")
plt.show()

自定义转换函数:

def konverter(tall):
    magnitude = 0
    while abs(tall) >= 1000:
        magnitude += 1
        tall /= 1000.0
    return '%.3f%s' % (tall, ['', 'K', 'Mn', 'Bn', 'Tn'][magnitude])

解决方案

1. 修复数值显示与柱子消失问题

柱子消失是因为直接用konverter修改原始数据后,小数值被处理成接近0的刻度,matplotlib自动隐藏了对应柱子。正确做法是保留原始数据用于绘图,仅用自定义函数修改x轴的刻度标签,通过FuncFormatter实现:

from matplotlib.ticker import FuncFormatter

# 适配函数为Formatter可接受的格式(需包含x和pos两个参数)
def format_bnp(x, pos):
    magnitude = 0
    while abs(x) >= 1000:
        magnitude += 1
        x /= 1000.0
    # 根据量级调整小数精度,避免显示冗余
    if magnitude >= 3:
        return '%.1f%s' % (x, ['', 'K', 'Mn', 'Bn', 'Tn'][magnitude])
    return '%.2f%s' % (x, ['', 'K', 'Mn', 'Bn', 'Tn'][magnitude])

# 将格式应用到x轴
plt.gca().xaxis.set_major_formatter(FuncFormatter(format_bnp))

2. 实现数据从小到大排序

要让横向柱状图从下到上按GDP从小到大排列,需先对国家和GDP数据按GDP值排序:

# 打包国家与GDP数据,按GDP值排序后拆分
sorted_pairs = sorted(zip(landStolpediagram, BNPStolpediagram), key=lambda x: x[1])
sorted_countries, sorted_bnp = zip(*sorted_pairs)

# 使用排序后的数据绘图
plt.barh(sorted_countries, sorted_bnp)

完整示例代码

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

def format_bnp(x, pos):
    magnitude = 0
    while abs(x) >= 1000:
        magnitude += 1
        x /= 1000.0
    # 按需调整小数精度
    if magnitude >= 3:
        return '%.1f%s' % (x, ['', 'K', 'Mn', 'Bn', 'Tn'][magnitude])
    return '%.2f%s' % (x, ['', 'K', 'Mn', 'Bn', 'Tn'][magnitude])

# 示例数据
landStolpediagram = ["Norge", "Sverige", "Danmark", "Island", "Luxembourg"]
BNPStolpediagram = [400000000000, 550000000000, 390000000000, 38000000000, 80000000000]

# 排序数据
sorted_pairs = sorted(zip(landStolpediagram, BNPStolpediagram), key=lambda x: x[1])
sorted_countries, sorted_bnp = zip(*sorted_pairs)

# 绘图
plt.barh(sorted_countries, sorted_bnp)
plt.xlabel("BNP")
plt.ylabel("Land")
plt.title("Dine valgte land og deres BNP verdi")

# 应用自定义刻度格式
plt.gca().xaxis.set_major_formatter(FuncFormatter(format_bnp))

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:22:58