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

标签 python matplotlib plot seaborn

也许我在做多面图表时太习惯了 R 的 ggplot 习惯用法(它不需要任何抗议就需要数字和字符串变量),但 ggplot 之外的理想方式肯定有我有一段时间未能了解 matplotlib 世界。

我通常会按多个维度对大量条形图进行分面,最近发现了基于 matplotlib 的著名seaborn 库,它具有简单的分面界面。

条形图通常需要 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:无法连接“str”和“float”对象

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)

适用于分类标签。在分面习语之外。)

最佳答案

sns.factorplotkind="bar" 结合使用。请参阅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

关于python - Matplotlib/Seaborn barplot——x 轴上的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26171230/

相关文章:

python - Pylons 1.0 和 SQLAlchemy 0.6 - 如何建模?

python - 为什么 Seaborn 绘制了两个图例,如何删除一个并修复另一个?

python - 无法导入 numpy : Error:/usr/lib/liblapack. so.3: undefined symbol: gotoblas

python - ValueError : expr must be a string to be evaluated, <class 'bool' > 给定

python - 在 pylab 中更改 numpy.sin(wt) 的振幅和频率

python - 如何检查 MPL 3d 使用什么坐标系?

python - 仅当位置可被给定值整除时,才使用 matplotlib.ticker.Locator 放置刻度

r - 仅命名小平面图中的第一个条形

Python pandas,多行的绘图选项

python - 如何查看 django sqlite3 db 的数据库和模式