Tushar Garg
Tushar Garg

Reputation: 81

Group bar plot together Pandas plot

I am new with Python plotting, and I am trying to group bars together using a pandas dataframe.

my input csv looks like this-- (test.csv)

noc,matrix,perf
jump4,dw,7.5
jump4,t2d,7.7
mesh,dw,2
mesh,t2d,4

and python plotting script is--

import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

df = pd.read_csv("test.csv", sep=",")
pp = PdfPages('rtl_sim_perf.pdf')

# gca stands for 'get current axis'
rc = {"axes.spines.top"    : False,
      "axes.spines.right"  : False,
      "axes.edgecolor"     : "black"}
plt.style.use(("ggplot", rc))
ax = plt.gca()

df.plot(x='matrix', y=['perf','noc'], ax=ax,kind='bar', edgecolor='k')
plt.xticks(fontsize=5,rotation=0)
plt.yticks(fontsize=5)
plt.legend(fontsize=7)
plt.tight_layout()
plt.savefig(pp, format='pdf')
pp.close()

and I get this result

enter image description here What I want is to group bars based on matrix column, so that dw are together for different noc and t2d together for different noc. And the legend shows me noc type. I am not sure how to do this.

Upvotes: 1

Views: 51

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

IIUC, do you want?

df.set_index(['matrix','noc'])['perf'].unstack().plot.bar()

Output:

enter image description here

You can achieve this by reshaping your dataframe such that you have 'noc' as columns in your dataframe and using pandas plot.


Another way is using seaborn and you don't have to reshape the dataframe and use the 'hue' parameter.

import seaborn as sns
sns.barplot(x='matrix', y='perf', hue='noc', data=df)

Output: enter image description here

Upvotes: 1

Related Questions