Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bar chart with ticks based on multiple dataframe columns

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading