Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a bar plot using Seaborn

I am trying to plot bar chart using seaborn. Sample data:

x=[1,1000,1001]
y=[200,300,400]
cat=['first','second','third']
df = pd.DataFrame(dict(x=x, y=y,cat=cat))

When I use:

sns.factorplot("x","y", data=df,kind="bar",palette="Blues",size=6,aspect=2,legend_out=False);

The figure produced is

No legend

When I add the legend

sns.factorplot("x","y", data=df,hue="cat",kind="bar",palette="Blues",size=6,aspect=2,legend_out=False);

The resulting figure looks like this

enter image description here

As you can see, the bar is shifted from the value. I don't know how to get the same layout as I had in the first figure and add the legend.

I am not necessarily tied to seaborn, I like the color palette, but any other approach is fine with me. The only requirement is that the figure looks like the first one and has the legend.

like image 556
Anastasia Avatar asked Apr 30 '15 06:04

Anastasia


1 Answers

It looks like this issue arises here - from the docs searborn.factorplot

hue : string, optional

Variable name in data for splitting the plot by color. In the case of ``kind=”bar, this also influences the placement on the x axis.

So, since seaborn uses matplotlib, you can do it like this:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

x=[1,1000,1001]
y=[200,300,400]
sns.set_context(rc={"figure.figsize": (8, 4)})
nd = np.arange(3)
width=0.8
plt.xticks(nd+width/2., ('1','1000','1001'))
plt.xlim(-0.15,3)
fig = plt.bar(nd, y, color=sns.color_palette("Blues",3))
plt.legend(fig, ['First','Second','Third'], loc = "upper left", title = "cat")
plt.show()

enter image description here

Added @mwaskom's method to get the three sns colors.

like image 189
AGS Avatar answered Oct 21 '22 11:10

AGS