简体   繁体   中英

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

在此处输入图像描述 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.

IIUC, do you want?

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

Output:

在此处输入图像描述

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: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM