Home > Back-end >  Bar chart with ticks based on multiple dataframe columns
Bar chart with ticks based on multiple dataframe columns

Time:03-04

How can I make a bar chart in matplotlib (or pandas) from the bins in my dataframe?

I want something like this, below, where the x-axis labels come from the low, high in my dataframe (so first tick would read [-1.089, 0) and the y value is the percent column in my dataframe.

enter image description here

Here is an example dataset. The dataset is already in this format (I don't have an uncut version).

df = pd.DataFrame(
    {
        "low": [-1.089, 0, 0.3, 0.5, 0.6, 0.8],
        "high": [0, 0.3, 0.5, 0.6, 0.8, 10.089],
        "percent": [0.509, 0.11, 0.074, 0.038, 0.069, 0.202],
    }
)
display(df)

enter image description here

CodePudding user response:

Recreate the bins using

CodePudding user response:

Create a new column using the the low, high cols.

Covert the int values in the low and high columns to str type and set the new str in the [<low>, <high>) notation that you want.

From there, you can create a bar plot dirrectly from df using df.plot.bar(), assigning the newly created column as x and percent as y.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.bar.html

  • Related