使用 Seaborn 创建条形图

Creating a bar plot using Seaborn

我正在尝试使用 seaborn 绘制条形图。示例数据:

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

当我使用:

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

产生的数字是

当我添加图例时

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

生成的图形如下所示

如您所见,条形图已从值偏移。我不知道如何获得与第一个图中相同的布局并添加图例。

我不一定喜欢 seaborn,我喜欢它的调色板,但任何其他方法都适合我。唯一要求是图和第一张一样,有图例。

看起来这个问题出现在这里 - 来自文档 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.

所以,由于seaborn使用matplotlib,你可以这样做:

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()

添加了@mwaskom 的方法来获取三种 sns 颜色。