Home > Mobile >  plot pandas Dataframe loaded from csv to barplot error
plot pandas Dataframe loaded from csv to barplot error

Time:08-08

I have a very simple file called classes_distribution.csv that was saved as csv file from a pandas dataframe. Such a file has one line of data as follows:

HUMAN,OTHER,SYMBOL,ABSTRACT,OBJECT,FLAG,PLANT,ANIMAL 65578,69372,51157,72559,59316,52337,60081,73700

I am trying to load the contents of such a file as a pandas dataframe again, and I am trying to plot the contents as a barplot. I don't want legends, that means, the x coordinate will contain the names of the classes (first line of the csv file), and the y axis will contain the number of occurrences (the second line of the csv file).

Here is what I tried to do

import pandas as pd
df=pd.read_csv("frames_stats_plots/classes_distribution.csv")
df.plot(legend=False).bar(x=df.columns, y=df.values).get_figure().savefig('plot.png')

which returns me the following error:

 File "<stdin>", line 1, in <module>
 File "/usr/local/lib/python3.10/dist-packages/matplotlib/__init__.py", line 1412, in inner
 return func(ax, *map(sanitize_sequence, args), **kwargs)
 TypeError: Axes.bar() missing 1 required positional argument: 'height'

What am I supposed to inform as height argument? how to solve this issue?

CodePudding user response:

Here is one way to do it:

import pandas as pd

df = pd.read_csv("frames_stats_plots/classes_distribution.csv")

# Reshape the dataframe so as to be suitable for a bar chart
df = df.T.reset_index().rename(columns={"index": "class", 0: "value"})

df.plot(kind="bar", x="class", y="value", legend=False)

Output:

enter image description here

  • Related