您如何通过Groupby进行绘图?

时间:2019-08-22 13:07:05

标签: python pandas-groupby

我想知道如何在“ new_build”组之间绘制条形图,X轴显示城镇,Y轴显示根据以下代码执行的计算得出的百分比值

  df_House.groupby(['new_build', 'town'])['price_paid'].count()/df_House.groupby(['new_build', 'town'])['price_paid'].count().sum()

1 个答案:

答案 0 :(得分:0)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

data = [['a', 'x', 100], ['b', 'y', 200], ['c', 'z', 300], ['a', 'y', 400], ['b', 'z', 600], ['c', 'x', 100]]
df = pd.DataFrame(data, columns=['new_build', 'town', 'price_paid'])

df_town = df.groupby(['new_build', 'town']).agg({'price_paid': 'sum'})
new_df = df_town.div(state, level='new_build') * 100
new_df.reset_index(inplace=True)

sns.set()
new_df.set_index(['new_build', 'town']).price_paid.plot(kind='bar', stacked=True)
plt.ylabel('% of price_paid')

enter image description here

不确定是否需要堆叠图来更好地表示数据,但为了使事情复杂化,我创建了一个执行所需任务的条形图。