Suresh Raja
Suresh Raja

Reputation: 745

Multiple Bar plots for each row data using Matplotlib

I have a dataframe as shown below:

PNO,SID,SIZE,N3IC,S4IC,N4TC,KPAC,NAAC,ECTC
SJV026,VIDAIC,FINE,0.0926,0.0446,0.0333,0.0185,0.005,0.0516
SJV028,CHCRUC,FINE,0,0.1472,0.0076,0.0001,0.0025,0.0301
SJV051,AMSUL,FINE,0,0.727,0.273,0,0,0
SJV035,MOVES1,FINE,0.02,0.04092,0,0,0,0.45404

I am looking to plot this using matplotlib or seaborn where there will be 'n' number of subplots for each row of data (that is one bar plot for each row of data).

import matplotlib.pyplot as plt
import pandas as pd
from tkinter.filedialog import askopenfilename
Inp_Filename = askopenfilename()
df = pd.read_csv(Inp_Filename)
rows, columns = df.shape
fig, axes = plt.subplots(rows, 1, figsize=(15, 20))

count = 0
for each in df.iterrows():
    row = df.iloc[count,3:]
    row.plot(kind='bar')

    count = count + 1

plt.show()

The above code output is not what I am looking for. Is there a way to plot each row of the data in the 'fig' and 'axes' above?

Upvotes: 1

Views: 1797

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339660

In principle the approach is correct. There are just a couple of errors in your code, which, when corrected, give the desired result.

import io
import matplotlib.pyplot as plt
import pandas as pd

u = u"""PNO,SID,SIZE,N3IC,S4IC,N4TC,KPAC,NAAC,ECTC
SJV026,VIDAIC,FINE,0.0926,0.0446,0.0333,0.0185,0.005,0.0516
SJV028,CHCRUC,FINE,0,0.1472,0.0076,0.0001,0.0025,0.0301
SJV051,AMSUL,FINE,0,0.727,0.273,0,0,0
SJV035,MOVES1,FINE,0.02,0.04092,0,0,0,0.45404"""

df = pd.read_csv(io.StringIO(u))
rows, columns = df.shape
fig, axes = plt.subplots(rows, 1, sharex=True, sharey=True)


for i, r in df.iterrows():
    row = df.iloc[i,3:]
    row.plot(kind='bar', ax=axes[i])

plt.show()

enter image description here

Upvotes: 1

Related Questions