pandas/matplotlib:刻面条形图

2024-05-23 15:06:58 发布

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

我用两个分类变量和一个数字绘制了一系列条形图。我有下面的内容,但是我想做的是用一个分类变量来切面,就像在ggplot中使用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

firstplot

不过,我想看到的是这样的情况:

## 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)

enter image description here

最接近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)

enter image description here

所以有两个问题:

  1. 我是否可以使用AxesSubplot对象进行条形图(它们按此处所示绘制线)并以类似于来自ggplot示例的facet_wrap示例的线结束
  2. 在生成此类图表的循环中,我在每个循环中对数据进行子集。我无法想象这是做这种刻面的“正确”方式?

Tags: citydfdataplotnpjobs绘制分类
2条回答

这里的第二个例子:http://pandas-docs.github.io/pandas-docs-travis/visualization.html#bar-plots

不管怎样,你可以像你自己一样,用手来做。

编辑: 顺便说一句,您可以在python中始终使用rpy2,这样您就可以做与R中相同的事情

还有,看看这个:http://pandas.pydata.org/pandas-docs/stable/rplot.html 我不确定,但它应该有助于在许多面板上创建绘图,尽管可能需要进一步阅读。

@tcasell建议在循环中调用bar。这是一个工作,如果不是优雅的例子。

## second try--facet by county

N = 100
industry = ['a','b','c']
city = ['x','y','z']
ind = np.random.choice(industry, N)
cty = np.random.choice(city, N)
jobs = np.random.randint(low=1,high=250,size=N)
df_city =pd.DataFrame({'industry':ind,'city':cty,'jobs':jobs})

## how many panels do we need?
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()
    print (data)
    print type(data.index)
    left=  [k[0] for k in enumerate(data)]
    right=  [k[1] for k in enumerate(data)]

    axes[x].bar(left,right,label="%s" % (city))
    axes[x].set_xticks(left, minor=False)
    axes[x].set_xticklabels(data.index.values)

    axes[x].legend(loc='best')
    axes[x].grid(True)
    fig.suptitle('Employment By Industry By City', fontsize=20)

enter image description here

相关问题 更多 >