【发布时间】:2013-10-27 00:44:09
【问题描述】:
我正在制作一系列带有两个分类变量和一个数字的数据条形图。我所拥有的是以下内容,但我想做的是通过facet_wrap 中的facet_wrap 中的一个分类变量来分面。我有一个可行的示例,但是我得到了错误的绘图类型(线条而不是条形),并且我在循环中对数据进行了子集化——这不是最好的方法。
## first try--plain vanilla
import pandas as pd
import numpy as np
N = 100
## generate toy data
ind = np.random.choice(['a','b','c'], N)
cty = np.random.choice(['x','y','z'], N)
jobs = np.random.randint(low=1,high=250,size=N)
## prep data frame
df_city = pd.DataFrame({'industry':ind,'city':cty,'jobs':jobs})
df_city_grouped = df_city.groupby(['city','industry']).jobs.sum().unstack()
df_city_grouped.plot(kind='bar',stacked=True,figsize=(9, 6))
这给出了这样的结果:
city industry jobs
0 z b 180
1 z c 121
2 x a 33
3 z a 121
4 z c 236
但是,我希望看到的是这样的:
## R code
library(plyr)
df_city<-read.csv('/home/aksel/Downloads/mockcity.csv',sep='\t')
## summarize
df_city_grouped <- ddply(df_city, .(city,industry), summarise, jobstot = sum(jobs))
## plot
ggplot(df_city_grouped, aes(x=industry, y=jobstot)) +
geom_bar(stat='identity') +
facet_wrap(~city)
我用 matplotlib 得到的最接近的是这样的:
cols =df_city.city.value_counts().shape[0]
fig, axes = plt.subplots(1, cols, figsize=(8, 8))
for x, city in enumerate(df_city.city.value_counts().index.values):
data = df_city[(df_city['city'] == city)]
data = data.groupby(['industry']).jobs.sum()
axes[x].plot(data)
所以两个问题:
- 我能否使用 AxesSubplot 对象绘制条形图(它们绘制线如图所示)并最终得到类似于来自
ggplot示例的 facet_wrap 示例的线条; - 在循环生成图表(如本次尝试)中,我对每个中的数据进行了子集化。我无法想象这是进行这种刻面的“正确”方式?
【问题讨论】:
-
为什么不在循环中使用
bar? -
@tcaswell,好建议。绘制条形图的技巧是什么?两个参数似乎都需要作为数字。先转换分类变量?有没有更规范的方式?
-
很抱歉回答了一个老问题,但我是通过谷歌搜索来到这里的。现在您可以使用 seaborn.FacetGrid 参见文档seaborn.pydata.org/generated/seaborn.FacetGrid.html 或本教程seaborn.pydata.org/tutorial/axis_grids.html
标签: python r matplotlib ggplot2 pandas