I have a count of green/orange/red by salesman for each customer : Something like :
sellor customer red green orange
0 73 c1 5 96 15
1 77 c1 88 18 79
2 97 c1 58 59 71
Which I can construct with :
df = pd.DataFrame()
df["sellor"] = np.random.randint(0,100, 20)
df["customer"] = ["c1"]*5 + ["C2"]*5 + ["C3"]*5 + ["c4"]*5
df["red"] = np.random.randint(0,100, 20)
df["green"] = np.random.randint(0,100, 20)
df["orange"] = np.random.randint(0,100, 20)
df.sellor = df.sellor.astype("category")
df.customer = df.customer.astype("category")
Now I want to represent the data as graphs : For now I do :
for customer in df.customer.unique():
df[df.customer==customer].plot.bar(title=customer)
Which gives me 4 images like the folowing one :
I think I could do the same with seaborn facetgrid, but didn't really find a way. I tried :
sns.barplot(data=df, x="sellor", y="red", hue="customer")
but it gives me only one plot (no subdivision by customer) + It doesn't gives me the 3 bars by sellors :(
How would I use a facetgrid to get the same result as my loop ?
Without using seaborn you may plot your barplots to different subplots of the same figure,
import matplotlib.pyplot as plt
u = df.customer.unique()
fig, axes = plt.subplots(ncols=len(u), figsize=(10,3))
for customer, ax in zip(u, axes):
df[df.customer==customer].plot.bar(x="sellor", title=customer, ax =ax )
plt.tight_layout()
plt.show()
You may achieve something similar with seaborn's FacetGrid via
import seaborn as sns
g = sns.FacetGrid(data=df, col="customer", col_order=["c1", "C2", "C3", "c4"])
def plot(*args,**kwargs):
kwargs["data"].plot(kind="bar", x="sellor", ax=plt.gca())
g.map_dataframe(plot)
plt.show()
Finally, to change the colors used here to match those of the dataframe names you may set the color cycle, e.g.
plt.rcParams["axes.prop_cycle"] = plt.cycler("color", ["red", "green", "orange"])