Python seaborn facetgrid
Python seaborn facetgrid
我有销售员为每个客户计算的 green/orange/red 的数量:
像这样的东西:
sellor customer red green orange
0 73 c1 5 96 15
1 77 c1 88 18 79
2 97 c1 58 59 71
我可以用 :
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")
现在我想将数据表示为图表:
现在我这样做了:
for customer in df.customer.unique():
df[df.customer==customer].plot.bar(title=customer)
这给了我 4 张图像,如下图所示:
我想我可以用 seaborn facetgrid 做同样的事情,但没有真正找到办法。
我试过了:
sns.barplot(data=df, x="sellor", y="red", hue="customer")
但它只给了我一个地块(没有按客户细分)+它没有给我卖家的 3 个酒吧:(
如何使用 facetgrid 获得与循环相同的结果?
在不使用 seaborn 的情况下,您可以将条形图绘制到同一图形的不同子图中,
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()
你可以通过
实现与seaborn的FacetGrid类似的东西
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()
最后,要更改此处使用的颜色以匹配数据框名称的颜色,您可以设置颜色循环,例如
plt.rcParams["axes.prop_cycle"] = plt.cycler("color", ["red", "green", "orange"])
我有销售员为每个客户计算的 green/orange/red 的数量: 像这样的东西:
sellor customer red green orange
0 73 c1 5 96 15
1 77 c1 88 18 79
2 97 c1 58 59 71
我可以用 :
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")
现在我想将数据表示为图表: 现在我这样做了:
for customer in df.customer.unique():
df[df.customer==customer].plot.bar(title=customer)
这给了我 4 张图像,如下图所示:
我想我可以用 seaborn facetgrid 做同样的事情,但没有真正找到办法。 我试过了:
sns.barplot(data=df, x="sellor", y="red", hue="customer")
但它只给了我一个地块(没有按客户细分)+它没有给我卖家的 3 个酒吧:(
如何使用 facetgrid 获得与循环相同的结果?
在不使用 seaborn 的情况下,您可以将条形图绘制到同一图形的不同子图中,
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()
你可以通过
实现与seaborn的FacetGrid类似的东西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()
最后,要更改此处使用的颜色以匹配数据框名称的颜色,您可以设置颜色循环,例如
plt.rcParams["axes.prop_cycle"] = plt.cycler("color", ["red", "green", "orange"])