5
votes

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.

1
Your "when I add the legend" line of code doesn't add a legend.cphlewis
You can get the colors in that palette by doing sns.color_palete("Blues", 3).mwaskom
Nice tip, @mwaskom! I'll add it to my answer below.AGS

1 Answers

9
votes

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.