Search code examples
pythonvisualizationaltair

Python Altair Bar Plots - How to change the number of bars?


I'm a newbie to Altair, and I would like to change the number of bars being plotted in a bar plot. I have done some research online, but couldn't find anything helpful. Here is my code:

import altair as alt
import pandas as pd
import numpy as np

# Generate a random np array of size 1000, and our goal is to plot its distribution.
my_numbers = np.random.normal(size = 1000)
my_numbers_df = pd.DataFrame.from_dict({'Integers': my_numbers})

alt.Chart(my_numbers_df).mark_bar(size = 10).encode(
    alt.X("Integers", 
          bin = True,
          scale = alt.Scale(domain=(-5, 5))
    ),
    y = 'count()',
)

The plot right now looks something like this enter image description here


Solution

  • You can increase the number of bins by passing an alt.Bin() object and specifying the maxbins

    import altair as alt
    import pandas as pd
    import numpy as np
    
    # Generate a random np array of size 1000, and our goal is to plot its distribution.
    my_numbers = np.random.normal(size = 1000)
    my_numbers_df = pd.DataFrame.from_dict({'Integers': my_numbers})
    
    alt.Chart(my_numbers_df).mark_bar(size = 10).encode(
        alt.X("Integers", 
              bin = alt.Bin(maxbins=25),
              scale = alt.Scale(domain=(-5, 5))
        ),
        y = 'count()',
    
    )
    

    histogram with 25 bins