Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bar chart race axis formating

Tags:

python

I have three columns in my dataset. 'Initial condition', 'Probability of A occurring given initial condition' and 'Probability of B occurring given initial condition'. I want a bar chart race animation gif in Python where I can show the progression of the bars (representing Probability of A and B) with changing initial condition. I tried doing this but the x-axis representing the values of the bar is either 0 or 1. I am unable to format it so that it gets shown in two decimal places. Would be really helpful if anyone can assist me. Here is the data sample.

enter image description here

Here is the code I used.

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()
like image 614
Abhi Raghu Avatar asked Aug 13 '26 17:08

Abhi Raghu


1 Answers

From what I understand, you have to set up manually the x-ticks using ax.set_xticks() from matplotlib package.

Here is a code snippet to show you the idea with dummy data:

import pandas as pd
import matplotlib.pyplot as plt
import bar_chart_race as bcr
import numpy as np
# Load the data
# data = pd.read_csv('data.csv')
N = 20
data = pd.DataFrame({'Initial captial of A': np.arange(N),
                     'Probability_A': np.linspace(0, 1, N),
                     'Probability B': np.linspace(1, 0, N)})
# Set the index to the starting capital of A
data = data.set_index('Initial captial of A')
print(data.head())

# Create the animated bar chart race
fig, ax = plt.subplots(1, 1, figsize=(8, 4), dpi=120, tight_layout=True)
bcr.bar_chart_race(
    df=data,
    filename='race.gif',
    orientation='h',
    sort='desc',
    n_bars=3,
    steps_per_period=1,
    interpolate_period=True,
    label_bars=True,
    bar_size=.95,
    period_length=1,
    dpi=144,
    fig=fig,
    title='Race',
    writer='pillow',
    fixed_max=True,
    fixed_order=['Probability_A', 'Probability B']
)
ax.set_xticks(np.linspace(0, 1, 10))
plt.show()

Let me know if you have further questions. Best regards.

like image 173
CamB04 Avatar answered Aug 15 '26 10:08

CamB04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!