Search code examples
pythonpandasplotlybar-chartplotly-express

How to make a barchart that doesn't start at y = 0


I want to make an barchart in python that has its own 'baseline', thus that the y-as doesn't start at 0 (as it usually does) but my chosen value.


Solution

  • You can use the bottom argument to matplotlib.pyplot.bar. This can be used in a plt.bar call or in pandas.DataFrame.plot.bar, which will pass keyword arguments through to matplotlib. The bottom argument will be added to all values in the dataframe, so you need to subtract it from the dataframe's values prior to plotting.

    For example:

    import pandas as pd, numpy as np
    years = np.arange(1880, 2022)
    df = pd.DataFrame({
        'co2_concentration': (
            np.sin((years / 50 - 1)* np.pi) * 0.2
            + np.arange(len(years)) / len(years)
            + 56.7
        )},
        index=years,
    )
    base = 57.1
    (df.co2_concentration - base).plot.bar(bottom=base, width=1)
    plt.xticks(range(0, len(years), 20))
    

    enter image description here