Giter VIP home page Giter VIP logo

bar_chart_race's Introduction

Bar Chart Race

PyPI - License

Make animated bar and line chart races in Python with matplotlib or plotly.

img

Official Documentation

Visit the bar_chart_race official documentation for detailed usage instructions.

Installation

Install with either:

  • pip install bar_chart_race
  • conda install -c conda-forge bar_chart_race

Quickstart

Must begin with a pandas DataFrame containing 'wide' data where:

  • Every row represents a single period of time
  • Each column holds the value for a particular category
  • The index contains the time component (optional)

The data below is an example of properly formatted data. It shows total deaths from COVID-19 for several countries by date.

img

Create bar and line chart races

There are three core functions available to construct the animations.

  • bar_chart_race
  • bar_chart_race_plotly
  • line_chart_race

The above animation was created with the help of matplotlib using the following call to bar_chart_race.

import bar_chart_race as bcr
df = bcr.load_dataset('covid19_tutorial')
bcr.bar_chart_race(
        df=df, 
        filename='../docs/images/covid19_horiz.gif', 
        orientation='h', 
        sort='desc', 
        n_bars=8, 
        fixed_order=False, 
        fixed_max=True, 
        steps_per_period=20, 
        period_length=500, 
        end_period_pause=0,
        interpolate_period=False, 
        period_label={'x': .98, 'y': .3, 'ha': 'right', 'va': 'center'}, 
        period_template='%B %d, %Y', 
        period_summary_func=lambda v, r: {'x': .98, 'y': .2, 
                                          's': f'Total deaths: {v.sum():,.0f}', 
                                          'ha': 'right', 'size': 11}, 
        perpendicular_bar_func='median', 
        colors='dark12', 
        title='COVID-19 Deaths by Country', 
        bar_size=.95, 
        bar_textposition='inside',
        bar_texttemplate='{x:,.0f}', 
        bar_label_font=7, 
        tick_label_font=7, 
        tick_template='{x:,.0f}',
        shared_fontdict=None, 
        scale='linear', 
        fig=None, 
        writer=None, 
        bar_kwargs={'alpha': .7},
        fig_kwargs={'figsize': (6, 3.5), 'dpi': 144},
        filter_column_colors=False) 

Save animation to disk or embed into a Jupyter Notebook

If you are working within a Jupyter Notebook, leave the filename as None and it will be automatically embedded into a Jupyter Notebook.

bcr.bar_chart_race(df=df, filename=None)

img

Customization

There are many options to customize the bar chart race to get the animation you desire. Below, we have an animation where the maximum x-value and order of the bars are set for the entire duration. A custom summary label and perpendicular bar of the median is also added.

def period_summary(values, ranks):
    top2 = values.nlargest(2)
    leader = top2.index[0]
    lead = top2.iloc[0] - top2.iloc[1]
    s = f'{leader} by {lead:.0f}'
    return {'s': s, 'x': .99, 'y': .03, 'ha': 'right', 'size': 8}

df_baseball = bcr.load_dataset('baseball').pivot(index='year',
                                                 columns='name',
                                                 values='hr')
df_baseball.bcr.bar_chart_race(
                   period_length=1000,
                   fixed_max=True, 
                   fixed_order=True, 
                   n_bars=10,
                   period_summary_func=period_summary,
                   period_label={'x': .99, 'y': .1},
                   period_template='Season {x:,.0f}',
                   title='Top 10 Home Run Hitters by Season Played')

img

bar_chart_race's People

Contributors

tdpetrou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bar_chart_race's Issues

findfont: Font family ['Helvetica'] not found. Falling back to DejaVu Sans.

Hi, I get this issue when I load the example script

findfont: Font family ['Helvetica'] not found. Falling back to DejaVu Sans.
findfont: Font family ['Helvetica'] not found. Falling back to DejaVu Sans.
findfont: Font family ['Helvetica'] not found. Falling back to DejaVu Sans.
D:\ProgramData\Anaconda3\lib\site-packages\bar_chart_race_make_chart.py:286: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_yticklabels(self.df_values.columns)
D:\ProgramData\Anaconda3\lib\site-packages\bar_chart_race_make_chart.py:287: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_xticklabels([max_val] * len(ax.get_xticks()))

I'm using python 3.8.5 and matplotlib 3.3.1

shaking of text of second bar

The text is shaking in the second bar with the following parameters. Will try to replicate the example with non-prop data.

bar_textposition='inside',
bar_texttemplate = 'K${x:,.1f}',
n_bars = 10,
bar_size = 0.9,
period_length = 250,
end_period_pause = 750,
steps_per_period = 3,

Baseball Example - ValueError: 'date' is not in list [ _make_chart.py in load_dataset(name)]

df_baseball = bcr.load_dataset('baseball')

ValueError Traceback (most recent call last)
in
7 return {'s': s, 'x': .95, 'y': .07, 'ha': 'right', 'size': 8}
8
----> 9 df_baseball = bcr.load_dataset('baseball')
10 df_baseball.head()

~/opt/anaconda3/lib/python3.7/site-packages/bar_chart_race/_make_chart.py in load_dataset(name)
371 '''
372 return pd.read_csv(f'https://raw.githubusercontent.com/dexplo/bar_chart_race/master/data/{name}.csv',
--> 373 index_col='date', parse_dates=['date'])

~/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
674 )
675
--> 676 return _read(filepath_or_buffer, kwds)
677
678 parser_f.name = name

~/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
446
447 # Create the parser.
--> 448 parser = TextFileReader(fp_or_buf, **kwds)
449
450 if chunksize or iterator:

~/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in init(self, f, engine, **kwds)
878 self.options["has_index_names"] = kwds["has_index_names"]
879
--> 880 self._make_engine(self.engine)
881
882 def close(self):

~/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in _make_engine(self, engine)
1112 def _make_engine(self, engine="c"):
1113 if engine == "c":
-> 1114 self._engine = CParserWrapper(self.f, **self.options)
1115 else:
1116 if engine == "python":

~/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in init(self, src, **kwds)
1947 _validate_usecols_names(usecols, self.names)
1948
-> 1949 self._set_noconvert_columns()
1950
1951 self.orig_names = self.names

~/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in _set_noconvert_columns(self)
2013 _set(k)
2014 else:
-> 2015 _set(val)
2016
2017 elif isinstance(self.parse_dates, dict):

~/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in _set(x)
2003
2004 if not is_integer(x):
-> 2005 x = names.index(x)
2006
2007 self._reader.set_noconvert(x)

ValueError: 'date' is not in list

Limelight on one or more categories

It will be nice to grab the attention of the viewer to one or more of the categories. For example, you can give the option to place a box only around the chosen categories or choose a highlight color that contrasts with others.

Increase Padding

After upgrading to version 0.2.0 the padding below the x-axis seems to have reduced.
What is the option to increase it back again ?

Before:
before

.
After:
after

Outside axis labels are slightly blury and look different from labels within the axis.

Hey Guys!

First off, thank you so much for all the work you've put in to this great tool!
Issue is basically described in the subject. The axis labels of all my plots are coming out a bit blurry.

Nothing crazy going on code wise, but here is the setup causing the issue:

  • Anaconda3
  • Jupyter Labs running on Windows

bcr.bar_chart_race(df=plot_df, fixed_max= True, n_bars=8, period_length=1000, dpi = 300, period_fmt='Year: {x:.0f}', title = "Popularity of Bachelor Degrees in the US from 1970 to 2017", tick_label_size=9, perpendicular_bar_func='mean', cmap='set3', filter_column_colors=True, )

test21

boolean index did not match indexed array along dimension 0; dimension is 11 but corresponding boolean dimension is 10

Hey @tdpetrou Thakns for making this! I'm trying to replicate the example tutorial plot but couldn't

import bar_chart_race as bcr
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('covid19_tutorial.csv')
plt.rcParams['ffmpeg_path'] = '/usr/local/Cellar/ffmpeg/4.2.2_3/bin'
bcr.bar_chart_race(df)

Error:

IndexError                                Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/bar_chart_race/_make_chart.py in make_animation(self)
    427             if self.html:
--> 428                 ret_val = anim.to_html5_video()
    429                 try:

~/Library/Python/3.7/lib/python/site-packages/matplotlib/animation.py in to_html5_video(self, embed_limit)
   1331                                 fps=1000. / self._interval)
-> 1332                 self.save(str(path), writer=writer)
   1333                 # Now open and base64 encode.

~/Library/Python/3.7/lib/python/site-packages/matplotlib/animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs, progress_callback)
   1134                     # Clear the initial frame
-> 1135                     anim._init_draw()
   1136                 frame_number = 0

~/Library/Python/3.7/lib/python/site-packages/matplotlib/animation.py in _init_draw(self)
   1745         else:
-> 1746             self._drawn_artists = self._init_func()
   1747             if self._blit:

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/bar_chart_race/_make_chart.py in init_func()
    419         def init_func():
--> 420             self.plot_bars(0)
    421 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/bar_chart_race/_make_chart.py in plot_bars(self, i)
    325         bar_location = bar_location[top_filt]
--> 326         bar_length = self.df_values.iloc[i].values[top_filt]
    327         cols = self.df_values.columns[top_filt]

IndexError: boolean index did not match indexed array along dimension 0; dimension is 11 but corresponding boolean dimension is 10

During handling of the above exception, another exception occurred:

Exception                                 Traceback (most recent call last)
<ipython-input-22-bdeaf7844271> in <module>
----> 1 bcr.bar_chart_race(df)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/bar_chart_race/_make_chart.py in bar_chart_race(df, filename, orientation, sort, n_bars, fixed_order, fixed_max, steps_per_period, period_length, interpolate_period, label_bars, bar_size, period_label, period_fmt, period_summary_func, perpendicular_bar_func, figsize, cmap, title, title_size, bar_label_size, tick_label_size, shared_fontdict, scale, writer, fig, dpi, bar_kwargs, filter_column_colors)
    781                         figsize, cmap, title, title_size, bar_label_size, tick_label_size,
    782                         shared_fontdict, scale, writer, fig, dpi, bar_kwargs, filter_column_colors)
--> 783     return bcr.make_animation()
    784 
    785 def load_dataset(name='covid19'):

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/bar_chart_race/_make_chart.py in make_animation(self)
    444             else:
    445                 message = str(e)
--> 446             raise Exception(message)
    447         finally:
    448             plt.rcParams = self.orig_rcParams

Exception: You do not have ffmpeg installed on your machine. Download
                            ffmpeg from here: https://www.ffmpeg.org/download.html.
                            
                            Matplotlib's original error message below:

                            boolean index did not match indexed array along dimension 0; dimension is 11 but corresponding boolean dimension is 10
                            

Change text format on the bars to float

Hi there!

I have a dataframe that the rate of changes is slow. So, I need to see how it changes through two decimals. Is there any way to change the format of the texts on the bars to float with specific decimals?

In the Github page, I've found:

bar_texttemplate='{x:,.0f}'

But I get keyword argument error since I guess it is removed. I cannot find the keyword in the documentation page.

Do you have any ideas how to do this?

Using Images as Labels for Each Bar

I checked that there is already a closed issue about this and that it is in the works. Is there any update? I want to show an image (circular if possible) for each category or bar instead of text. For example, for the covid-19 dataset, I would like to be able to show country flags instead of the name (or maybe both would also be useful).

If I wanted to make this addition myself, where in the code would be the best place to start working on? Is this a feature of matplotlib?

X-axis label number format

Hi,

is there a way to change the number format in X-axis?, in my country the comma is used as decimal separator, I tried to fix this with the import of locale library, but the issue continues...

Showing exponential

Hi,

Is there way to show float numbers that contains big exponential. Currently, its showing plain number which is too big to fit into the picture

Bars Overlap Each Other During Animation

Hello, I have been trying this library to animate data I collected about my puppies while they were growing. However, I have a problem where many of the bars overlap with each other.

The dataset has 9 different dogs, and about 200 data points per dog (there are many NaN values in between). Do you have any suggestions about what could be the issue?

Can it run without FFMPEG?

Exception: You do not have ffmpeg installed on your machine. Download
                            ffmpeg from here: https://www.ffmpeg.org/download.html.

I'm trying to run the example code as shown in the README.md, however, I'm getting the above error.

I am on Windows, and have already installed ffmpeg, and included it in my Path variables.

Is there anyway to run without ffmpeg?

Bar labels only show integers but floats

Hi. Thank you for developing it.
I need to show percentages next to the bars but it only showed integers rather than floats. Can you add an option to change the format?
Also, the ticks have no shading color and they will overlie each other when they meet and people can see neither. Can you add shading color so people can see at least one of them? Thank you.

X-Axis to include nagative values. It follows that "fixed_min" will be good to have.

Hi Ted,

Very good API ... Thanks a lot !!

I would request that you permit X-Axis to include negative values as well. If you were to include then it follows that the "fixed_min" will be good to have just like you have "fixed_max".

The use case where say I'm plotting return of a group of stocks, and some of them have negative return that I'd like to plot. (In case of Covid deaths and Home Runs it's all expressed as positive X-Axis values, however there are instances of negatives as well.) Another use case could be where we're plotting the Average Temperatures of Chicago, Houston, San Francisco, Los Angeles etc. recorded on Jan1, Feb 2, Mar 1, etc.

Thanks.
~ Salil

install bar-chart-race 0.1.0, python3.8 unable to run demo

module:
matplotlib 3.3.2
pandas 1.1.3
Pillow 7.2.0
bar-chart-race 0.1.0

df = bcr.load_dataset('covid19_tutorial')
print(df)
bcr.bar_chart_race(df, 'f.gif')

errors occurred
Belgium China France ... Spain USA United Kingdom
date ...
2020-04-03 1143 3326 6520 ... 11198 7418 3611
2020-04-04 1283 3330 7574 ... 11947 8387 4320
2020-04-05 1447 3333 8093 ... 12641 9489 4943
2020-04-06 1632 3335 8926 ... 13341 10783 5385
2020-04-07 2035 3335 10343 ... 14045 12798 6171
2020-04-08 2240 3337 10887 ... 14792 14704 7111
2020-04-09 2523 3339 12228 ... 15447 16553 7993
2020-04-10 3019 3340 13215 ... 16081 18595 8974
2020-04-11 3346 3343 13851 ... 16606 20471 9892
2020-04-12 3600 3343 14412 ... 17209 22032 10629

[10 rows x 10 columns]
D:\PycharmProjects\barTest\venv\lib\site-packages\bar_chart_race_make_chart.py:286: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_yticklabels(self.df_values.columns)
D:\PycharmProjects\barTest\venv\lib\site-packages\bar_chart_race_make_chart.py:287: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_xticklabels([max_val] * len(ax.get_xticks()))
MovieWriter imagemagick unavailable; using Pillow instead.
0 [ 1. 5. 7. 2. 4. 10. 3. 9. 8. 6.]
0 [ 1. 5. 7. 2. 4. 10. 3. 9. 8. 6.]
Traceback (most recent call last):
File "D:\PycharmProjects\barTest\venv\lib\site-packages\matplotlib\animation.py", line 251, in saving
yield self
File "D:\PycharmProjects\barTest\venv\lib\site-packages\matplotlib\animation.py", line 1145, in save
writer.grab_frame(**savefig_kwargs)
File "D:\PycharmProjects\barTest\venv\lib\site-packages\matplotlib\animation.py", line 549, in grab_frame
renderer = self.fig.canvas.get_renderer()
AttributeError: 'FigureCanvasBase' object has no attribute 'get_renderer'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\PycharmProjects\barTest\venv\lib\site-packages\bar_chart_race_make_chart.py", line 437, in make_animation
ret_val = anim.save(self.filename, fps=self.fps, writer=self.writer)
File "D:\PycharmProjects\barTest\venv\lib\site-packages\matplotlib\animation.py", line 1145, in save
writer.grab_frame(**savefig_kwargs)
File "D:\python\Python38-32\lib\contextlib.py", line 131, in exit
self.gen.throw(type, value, traceback)
File "D:\PycharmProjects\barTest\venv\lib\site-packages\matplotlib\animation.py", line 253, in saving
self.finish()
File "D:\PycharmProjects\barTest\venv\lib\site-packages\matplotlib\animation.py", line 554, in finish
self._frames[0].save(
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:/PycharmProjects/barTest/barTest.py", line 10, in
bcr.bar_chart_race(df, 'f.gif')
File "D:\PycharmProjects\barTest\venv\lib\site-packages\bar_chart_race_make_chart.py", line 785, in bar_chart_race
return bcr.make_animation()
File "D:\PycharmProjects\barTest\venv\lib\site-packages\bar_chart_race_make_chart.py", line 448, in make_animation
raise Exception(message)
Exception: list index out of range

Doesn't support other fonts

there is problem with support of font, in my case, i am working on hindi fonts ['hi']. it looks like this
image

How can I plot from smallest to the largest values?

Hello,

I am trying to plot the bottom 10 categories from my dataset. I am changing the sort attribute to 'asc' and then it just plots the top 10 categories in ascending order,
let's say we have 5 categories e.g.
Category | Value
category 1| 1
category 2| 2
category 3| 3
category 4| 4
category 5| 5

and I want to plot (animate) the bottom 3. If I change the sort to attribute to asc then the plot is like this:
category 3| 3
category 4| 4
category 5| 5

but it should have been
category 1| 1
category 2| 2
category 3| 3

Do you have any idea how to fix this?

Thanks a lot,
Andreas

Bar Label Formatting

Excellent work!
It looks like it isn't possible to format the Bar Labels while it's sometimes necessary to display float.

Only show entries above a certain threshold in the bar chart race

The package is super, thanks!
I suggest implementing a feature to only show entries above a certain threshold in the bar chart race. To explain what I mean, let's consider the COVID-19 pandemic. Let's assume that I set the threshold to 0, i.e. only show countries with more that 0 COVID-19 cases/deaths. In the beginning, the bar chart race would only include China, but as the virus is spreading more and more countries would "enter" the bar chart race once the threshold is met. This would be a super useful feature in cases where many entries have zero (or low) starting values.

This could be combined with an "nminbars" parameter, which would overrule the threshold value, so that one could force minimum, say, 5 entries in the race, but more would be added once the threshold is met (until the nmaxbars is reached).

OSX Catalina Version 10.15.4 error -> dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Context: macOS OSX Catalina Version 10.15.4

  • Anaconda (latest using 3.7)

MovieWriter stderr:
dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /usr/local/bin/ffmpeg
Reason: image not found


Looks like a Mac OS configuration issue. Have tried reinstalling FFmpeg via
brew reinstall FFmpeg per # see this link - https://stackoverflow.com/questions/60745450/trouble-with-ffmpeg-on-mac-os-catalina-10-15-3

I don't think it has to do with your code but something about this matplotlib.animation library and latest version of OSX issues.

Your code works great via Colab. Great package. Thank you for creating this

Trying df = bcr.load_dataset('urban_pop') -> ValueError: 'date' is not in list

Context: Colab Notebook

df = bcr.load_dataset('urban_pop')
df

ValueError Traceback (most recent call last)
in ()
----> 1 df = bcr.load_dataset('urban_pop')
2 df

7 frames
/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py in _set(x)
2003
2004 if not is_integer(x):
-> 2005 x = names.index(x)
2006
2007 self._reader.set_noconvert(x)

ValueError: 'date' is not in list

Specify fixed color to Bars

In my use case, I want to use custom colors per bar.

So, altogether I wanna use only two colors for my bars.

Tried to use the following in my chart which has 14 bars,
cmap = (["green"] * 7) + (["red"] * 7)

Great! this assigns the colors to bars in Order too!

Index location - make adjustable?

First of all, thanks for putting this together, it's a really easy-to-use and effective way to produce a good-looking bar chart race.

Is it possible to make the location of the index when use_index=True adjustable? For the video I created the index (in this case the year) overlaps with the bottom bars.

This is the code I used in Jupyter. The full Notebook is here

    df=income_new,
    filename='income.mp4',
    period_length=250,
    title='GDP per capita (in 2011 USD)',
    n_bars=10)

This is just a suggestion for an improvement. If there were an argument that could be passed with a few different options (eg right, centre, left, upper_right, lower_right) that would allow the user to avoid this issue.

Thanks again for your work on this package.

Outside axis labels are slightly blury and look different from labels within the axis.

Hey Guys!

First off, thank you so much for all the work you've put in to this great tool!
Issue is basically described in the subject. The axis labels of all my plots are coming out a bit blurry.

Nothing crazy going on code wise, but here is the setup causing the issue:

  • Anaconda3
  • Jupyter Labs running on Windows

bcr.bar_chart_race(df=plot_df, fixed_max= True, n_bars=8, period_length=1000, dpi = 300, period_fmt='Year: {x:.0f}', title = "Popularity of Bachelor Degrees in the US from 1970 to 2017", tick_label_size=9, perpendicular_bar_func='mean', cmap='set3', filter_column_colors=True, )

Race in Plotly

Hello all, can anyone tell me how to save the race in plotly, like the second graph on https://www.dexplo.org/bar_chart_race/ with title "COVID-19 Bar Chart Race with Plotly" and Play and Pause buttons. For me already works the bar chart race but exporting to mp4, gif or html.

Best regards.

Package Version


bar-chart-race 0.2.0

Bar was overlapping and just hold the position

Hello, I have some problem :)

스크린샷 2021-04-16 오후 5 36 49

bcr.bar_chart_race( df=df, orientation='h', sort='desc', n_bars=10, fixed_order=False, fixed_max=True, steps_per_period=4, label_bars=True, bar_size=.55, filter_column_colors=False, figsize=(5,4))

This is my data.

스크린샷 2021-04-16 오후 6 11 23

Bar was overlapping and just hold the position
I want to go down when bar number is lower than others.
Thanks.

Maybe a have a preview / draft keyword argument

Nice package! One suggestion I have is to have a preview keyword that either only does the head of the pandas dataframe or have it skip half the frames because after taking a while to export the gif, I realized the labels were all crammed and the data doesn't really start until a later date (i.e. the bars were all at 0).

Shaking of Y Ticks and Y-Axis

Hey Guys!

First of all, thank you so much for your effort with this great tool!

The issue is basically described in the subject. The y-axis labels of all my plots are shaking if any label has a different number of strings and changes the order while racing.

For instance, I have 40 data and I choose the top 10. In the beginning, the longest string is "UC Browser" in the screenshot. Therefore, the y-label space on the left-hand side uses "UC Browser" to calculate the space. However, after a few seconds, the "360 Safe Browser" is in the top 10. But the string length is longer than the previous one. I guess it causes the different sizes of the plot and the width of the x-axis, and it will shake after it generates the animation. Please kindly refer to the below image.

Issue_BarChartRace (1)

Do you have any idea how to fix the position of the y-axis or the width of the x-axis? Or can we get the longest string number throughout all data and use it to set up space on the left-hand side even that label is not in the top 10 rankings?

Feel free to let me know if you have any suggestions. I truly appreciate your assistance.

Add requirement.txt

First of all thank you for this contribution! We needed this on python too.

Do you mind to add a requirement.txt in your main?

# requirement.txt
pandas
numpy
matplotlib

I'm now writing a conda package for this library but in case you change some dependencies have them in a file will be easier to manage.

About bar_label_fmt

Is there any guide about how to use this?
For example, If I want show 1 decimal place, how should I do?

FixedFormatter / FixedLocator error with example code

Hello,

I am trying to run the example code provided.

import bar_chart_race as bcr
df = bcr.load_dataset('covid19_tutorial')
bcr.bar_chart_race(
        df=df, 
        filename='../docs/images/covid19_horiz.gif', 
        orientation='h', 
        sort='desc', 
        n_bars=8, 
        fixed_order=False, 
        fixed_max=True, 
        steps_per_period=20, 
        period_length=500, 
        end_period_pause=0,
        interpolate_period=False, 
        period_label={'x': .98, 'y': .3, 'ha': 'right', 'va': 'center'}, 
        period_template='%B %d, %Y', 
        period_summary_func=lambda v, r: {'x': .98, 'y': .2, 
                                          's': f'Total deaths: {v.sum():,.0f}', 
                                          'ha': 'right', 'size': 11}, 
        perpendicular_bar_func='median', 
        colors='dark12', 
        title='COVID-19 Deaths by Country', 
        bar_size=.95, 
        bar_textposition='inside',
        bar_texttemplate='{x:,.0f}', 
        bar_label_font=7, 
        tick_label_font=7, 
        tick_template='{x:,.0f}',
        shared_fontdict=None, 
        scale='linear', 
        fig=None, 
        writer=None, 
        bar_kwargs={'alpha': .7},
        fig_kwargs={'figsize': (6, 3.5), 'dpi': 144},
        filter_column_colors=False) 

After installing everything (including ffmpeg) I always get these 2 errors:

UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_yticklabels(self.df_values.columns)

UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_xticklabels([max_val] * len(ax.get_xticks()))

Is there any way around this? I find it a bit weird that the example code is not working properly.

Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.