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

Python条形图竞速动画x轴格式求助:设置两位小数

问题描述

我有一个包含三列的数据集:Initial condition、Probability of A occurring given initial condition、Probability of B occurring given initial condition。想用Python制作条形图竞速动画GIF,展示随着Initial condition变化时,A、B发生概率的条形图变化过程。但目前x轴仅显示0或1,无法设置为两位小数,需要技术协助。

使用的代码如下:

import pandas as pd
import matplotlib.pyplot as plt
import bar_chart_race as bcr

# Load the data
data = pd.read_csv('data.csv')

# Set the index to the starting capital of A
data = data.set_index('Initial captial of A')

# Create the animated bar chart race
bcr.bar_chart_race(
    df=data,
    filename='race.gif',
    orientation='h',
    sort='desc',
    n_bars=3,
    steps_per_period=10,
    interpolate_period=False,
    label_bars=True,
    bar_size=.95,
    period_length=500,
    figsize=(6, 3),
    dpi=144,
    title='Race',
    writer='pillow'
)

plt.show()
解决方法

要让x轴显示两位小数,可借助bar_chart_race的post_process_func参数自定义坐标轴格式,具体修改如下:

修改后的代码:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import bar_chart_race as bcr

# 加载数据
data = pd.read_csv('data.csv')

# 修正索引名,匹配数据集的列名
data = data.set_index('Initial condition')

# 定义x轴刻度格式化函数,保留两位小数
def format_x_ticks(value, pos):
    return f"{value:.2f}"

# 生成条形图竞速动画
bcr.bar_chart_race(
    df=data,
    filename='race.gif',
    orientation='h',
    sort='desc',
    n_bars=2,  # 仅A、B两个类别,设置为2更合理
    steps_per_period=10,
    interpolate_period=False,
    label_bars=True,
    bar_size=.95,
    period_length=500,
    figsize=(6, 3),
    dpi=144,
    title='A、B发生概率随初始条件变化',
    writer='pillow',
    # 自定义每个帧的坐标轴格式
    post_process_func=lambda ax: ax.xaxis.set_major_formatter(FuncFormatter(format_x_ticks))
)

plt.show()

关键修改说明:

  • 修正索引名:原代码中Initial captial of A拼写错误,改为匹配数据集的Initial condition,避免索引设置异常。
  • 添加刻度格式化函数:用FuncFormatter自定义x轴刻度显示为两位小数。
  • 调整n_bars为2:因为只有A、B两个类别,减少多余空条形的显示。
  • 使用post_process_func:该参数会在每个动画帧绘制完成后执行,确保x轴格式在所有帧中生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:43:13