Как предотвратить сбои в анимации bar_chart_race с помощью динамического масштабирования по оси X (fixed_max=False)Python

Программы на Python
Ответить
Anonymous
 Как предотвратить сбои в анимации bar_chart_race с помощью динамического масштабирования по оси X (fixed_max=False)

Сообщение Anonymous »

Я создаю видео с гонками на гистограмме, используя пакет bar_chart_race в Python, но столкнулся с проблемой при переключении параметра fix_max. Если для параметра fix_max установлено значение True, видео выглядит плавным и стабильным. Однако установка значения False приводит к сбоям, особенно когда большие значения (например, 1000, 2000, 5000, 10000) добавляются по оси X. Я хотел бы лучше понять, почему это происходит и как сделать визуализацию данных более эффективной, когда fix_max=False.
Я попробовал установить для параметра fix_max значение False, чтобы ось X могла динамически корректироваться. к диапазону данных, ожидая более плавного эффекта масштабирования. Однако это изменение привело к сбоям во время воспроизведения. Я ожидал, что гистограмма будет плавно обрабатывать динамически изменяющиеся пределы оси X, но вместо этого она нарушила анимацию. Буду признателен за любые предложения по устранению этой проблемы или улучшению визуализации данных.
Вот соответствующий код:

Код: Выделить всё

import bar_chart_race as bcr
import pandas as pd
import warnings
from datetime import datetime

# Get the current time and format it
current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

# Ignore all warnings
warnings.filterwarnings("ignore")

df = pd.read_csv("raw_data.csv", index_col="Date",parse_dates=["Date"], dayfirst=True)

# replace empty values with 0
df.fillna(0.0, inplace=True)

# Apply a moving average with a window size adjust as needed
df_smooth = df.rolling(window=10, min_periods=1).mean()

# Define the output filename
filename = f'YouTube Subscriber Growth {current_time}.mp4'

# using the bar_chart_race package
bcr.bar_chart_race(
# must be a DataFrame where each row represents a single period of time.
df=df_smooth,

# name of the video file
filename=filename,

# specify location of image folder
img_label_folder="YT Channel Images",

# change the Figure properties
fig_kwargs={
'figsize': (26, 15),
'dpi': 120,
'facecolor': '#D3D3D3'
},

# orientation of the bar: h or v
orientation="h",

# sort the bar for each period
sort="desc",

# number of bars to display in each frame
n_bars=5,

# If set to True, this smoothens the transition between periods by interpolating values
# during each frame, making the animation smoother. This is useful when there are significant
# changes in data between periods, and it ensures that the bars move more fluidly.
interpolate_period=True,

# to fix the maximum value of the axis
fixed_max=False,

# smoothness of the animation
steps_per_period=90,

# time period in ms for each row
period_length=1500,

# custom set of colors
colors=[
'#FF4500', '#DC143C', '#F08080', '#FF6347',
'#00BFFF', '#1E90FF', '#7B68EE', '#00FFFF',
'#00FA9A', '#7CFC00', '#32CD32', '#2E8B57',
'#FFD700', '#FAFAD2', '#FFFACD', '#F0E68C',
'#EE82EE', '#BA55D3', '#8A2BE2', '#663399'],

# title and its styles
title={'label': 'YouTube Subscriber Growth',
'size': 52,
'weight': 'bold',
'pad': 40
},

# adjust the position and style of the period label
period_label={'x': .95, 'y': .15,
'ha': 'right',
'va': 'center',
'size': 72,
'weight': 'semibold'
},

# style the bar label text
bar_label_font={'size': 27},

# style the labels in x and y axis
tick_label_font={'size': 27},

# adjust the style of bar
# alpha is opacity of bar
# ls - width of edge
bar_kwargs={'alpha': .99, 'lw': 0},

# adjust the bar label format
bar_texttemplate='{x:.0f}',

# adjust the period label format
period_template='%B %d, %Y',
)
print("Chart creation completed.  Video saved as", filename, sep=' ',end='.')
https://drive.google.com/file/d/1mxfWe4 ... drive_link
Ввод данных (raw_data.csv) :
https://drive.google.com/file/d/1gVc9_z ... drive_link
Вывод видео:< /p>
С фиксированным_максимумом:
https://drive.google.com/file/d/1L1BnqY ... drive_link< /p>
Без фиксированного_макс:
https://drive.google.com/file/d/1dPa18P ... drive_link< /п>

Подробнее здесь: https://stackoverflow.com/questions/791 ... is-scaling
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»