Matplotlib/Seaborn barplot—x轴上的字符串

2024-06-28 19:46:23 发布

您现在位置:Python中文网/ 问答频道 /正文

也许我已经习惯了在制作分面图时使用R's美妙的ggplot-习惯用法(它不带抗议地接受数值和字符串变量),但在了解matplotlib世界的一段时间里,ggplot之外的理想方式肯定让我难以理解。

我通常按几个维度划分很多条形图,最近发现著名的seaborn图书馆建立在matplotlib上,它有一个简单的划分界面。

条形图通常需要x变量的数值向量(与分类字符串向量相反),这里首先是一些模拟数据和基本图:

import pandas as pd
import numpy as np
import seaborn as sns
N = 100

## generate toy data
ind = np.random.choice(['retail','construction','information'], N)
cty = np.random.choice(['cooltown','mountain pines'], N)
age = np.random.choice(['young','old'], N)
jobs = np.random.randint(low=1,high=250,size=N)

## prep data frame
df_city = pd.DataFrame({'industry':ind,'city':cty,'jobs':jobs,'age':age})
df_city_grouped = df_city.groupby(['city','industry','age']).sum()
df_city_grouped.unstack().plot(kind='bar',stacked=True,figsize=(9, 6),title='Jobs by city, industry, age group')

这就产生了这个情节。这种数据帧打印方法可以使用索引在后台打印: matplotlib plot

现在,转到seaborn,它有一个很好的刻面界面。 首先,我将多索引展平,这样就有了列(我认为这是API所必需的)。

df_city_grouped.reset_index(inplace=True)
df_city_grouped.head()

+----------+--------------+-------+------+
| city     | industry     | age   | jobs |
+----------+--------------+-------+------+
| cooltown | construction | old   | 563  |
+----------+--------------+-------+------+
| cooltown | construction | young | 1337 |
+----------+--------------+-------+------+
| cooltown | information  | old   | 1234 |
+----------+--------------+-------+------+
| cooltown | information  | young | 1402 |
+----------+--------------+-------+------+
| cooltown | retail       | old   | 1035 |
+----------+--------------+-------+------+

调用此函数将给出错误TypeError: cannot concatenate 'str' and 'float' objects

g = sns.FacetGrid(df_city_grouped, col="industry", row="city", margin_titles=True)
g.map(plt.bar, "age","jobs", color="darkred", lw=0)

但是,我可以破解它并将其中一个分类变量返回到一个数字:

mapping = {
'young': 1,
'middle':2,
'old':3}

df_city_grouped['age2']=df_city_grouped.age.map(mapping) 
g = sns.FacetGrid(df_city_grouped, col="industry", row="city", margin_titles=True)
g.map(plt.bar, "age2","jobs", color="darkred", lw=0)

从而得到近似结果(但是x上有小数)。 seaborn plot with numeric axis 所以我的问题是——在刻面示例中,处理分类轴的最佳方法是什么?(顺便说一下

f, (ax) = plt.subplots()
sns.barplot(df_city_grouped.industry, df_city_grouped.jobs, ax=ax, ci=None)

确实适用于分类标签。在faceting习惯用法之外。)


Tags: truecitydfagenpjobs分类random
1条回答
网友
1楼 · 发布于 2024-06-28 19:46:23

kind="bar"一起使用sns.factorplot。有关详细信息,请参见docs,但下面是一个数据示例:

sns.factorplot("age", "jobs", col="industry", row="city", data=df_city,
               margin_titles=True, size=3, aspect=.8, palette=["darkred"])

enter image description here

相关问题 更多 >