也許我太習慣於R's
精彩ggplot
-idiom當做分面圖表(它需要數字和字符串變量而沒有抗議),但ggplot之外的理想方式已經無法爲我時間瞭解matplotlib世界。Matplotlib/Seaborn barplot - x軸中的字符串
我通常用多個維度刻劃很多條形圖,並且最近在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')
其中產量該地塊。該地塊的數據幀的方法可以使用索引的幕後陰謀:
現在,到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小數)。 所以我的問題是 - 在面向示例中處理分類軸的最佳方式是什麼? (順便指出,
f, (ax) = plt.subplots()
sns.barplot(df_city_grouped.industry, df_city_grouped.jobs, ax=ax, ci=None)
確實與分類標籤的工作。在小面成語之外。)
通過你也可能映射到''FacetGrid'的sns.barplot'方式。沒有任何理由使用'factorplot',但是您可以將任何函數傳遞給'FacetGrid.map',它不必位於'plt'命名空間中。 – mwaskom 2014-10-04 00:51:59
很酷的東西。 API非常整潔。 – ako 2014-10-04 02:46:02