熊猫绘制按时间分组的条形图

时间:2018-06-11 01:30:19

标签: python pandas matplotlib

我在下面有一张表格,我想在一个分组的条形图中绘制。我希望x轴为time_period,y轴为death_licenses,我希望按civic_centre进行分类。如您所见,对于每个不同的time_periodcivic_centre中有四个分类选项。

+-------------+--------------+----------------+
| time_period | civic_centre | death_licenses |
+-------------+--------------+----------------+
| 2011-01-01  | ET           |            410 |
| 2011-01-01  | NY           |            681 |
| 2011-01-01  | SC           |            674 |
| 2011-01-01  | TO           |            297 |
| 2011-02-01  | ET           |            307 |
| 2011-02-01  | NY           |            388 |
| 2011-02-01  | SC           |            407 |
| 2011-02-01  | TO           |            223 |
| 2011-03-01  | ET           |            349 |
| 2011-03-01  | NY           |            655 |
| 2011-03-01  | SC           |            400 |
| 2011-03-01  | TO           |            185 |
| 2011-04-01  | ET           |            373 |
| 2011-04-01  | NY           |            640 |
| 2011-04-01  | SC           |            457 |
| 2011-04-01  | TO           |             42 |
+-------------+--------------+----------------+

这是我到目前为止所做的工作:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class Utility:

@staticmethod
def read_csv(csv, number_columns=[], categorical_columns=[], date_columns=[], drop_columns_if_empty=[], drop_duplicate_columns=[]):
    df = pd.read_csv(csv, na_values=['--', ''])
    df.rename(columns=lambda x: x.strip().replace('"', '').replace(' ', '_').replace('__', '_').lower(),
              inplace=True)
    df[number_columns] = df[number_columns].astype(str).replace({'[\$,)]': '', ' ': '', '[(]': '-'}, regex=True)
    for col in number_columns:
        df[col] = pd.to_numeric(df[col], errors='coerce')
    for col in date_columns:
        df[col] = pd.to_datetime(df[col], errors='coerce')

    df.dropna(subset=drop_columns_if_empty, how='any', inplace=True)
    df = df.applymap(lambda x: x.strip() if type(x) is str else x)
    if (len(drop_duplicate_columns) > 1):
        df = df.drop_duplicates(drop_duplicate_columns, keep='last')
    for col in categorical_columns:
        df[col] = pd.Categorical(df[col])

    return df

df = Utility.read_csv('http://opendata.toronto.ca/clerk/registry.service/death.csv', number_columns=['death_licenses'], categorical_columns=['place_of_death', 'civic_centre'], date_columns=['time_period'])
df.sort_values(['time_period', 'civic_centre'], ascending=[True, False])
df2 = df.groupby(['time_period', 'civic_centre'])['death_licenses'].agg('sum').reset_index()

我想做这样的事情: grouped bar graph

1 个答案:

答案 0 :(得分:3)

这里有几个绘图选项(如果我理解正确的话),我更喜欢第一个自己。

% matplotlib inline

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from pandas import Series, DataFrame

civics = ([i for i in ['ET', 'NY', 'SC', 'TO']] * 4)
civics.sort()

data = DataFrame({
    'time_period': Series([pd.to_datetime('2011-0{}-01'.format(i)) for i in 
range(1, 5)] * 4),
    'civic_centre': Series(civics),
    'death_licenses': Series(np.random.randint(400, 500, 16))
})

# As four series.

pd.pivot_table(data, index = 'time_period', columns = 'civic_centre', values 
= 'death_licenses').plot();

# As a grouped bar plot.

pd.pivot_table(data, index = 'civic_centre', columns = 'time_period', values 
= 'death_licenses').plot(kind = 'bar')

给出这两个图:

enter image description here