简体   繁体   中英

Stacked Bar Plot from Dataframe in Pandas

I'm trying to make a stacked bar graph where the x-axes are customer names, the y axes are the number of calls, and the stacks are the months.

I have made a pivot_table that looks like this:

pivot_table.head(3)

Out[23]: 
Month                      1   2   3   4   5   6   7   8   9   10  11  12
CompanyName                                                              
Company1   11   3   2   3   5   7   3   6   8   3   5   8
Company2   3   1   2  18   3   4   5   4   5   5   3   2
Company3   2   6   1   3   2   0   5   6   4   8   4   7

Here is the code

df = pd.read_csv('MYDATA.csv')
df = df.set_index('recvd_dttm')
df.index = pd.to_datetime(df.index, format='%m/%d/%Y %H:%M')

result = df.groupby([lambda idx: idx.month, 'CompanyName']).agg(len).reset_index()
result.columns = ['Month', 'CompanyName', 'NumberCalls']
pivot_table = result.pivot(index='Month', columns='CompanyName', values='NumberCalls').fillna(0)
s = pivot_table.sum().sort(ascending=False,inplace=False)
pivot_table = pivot_table.ix[:,s.index[:40]]
pivot_table = pivot_table.transpose()



pivot_table = pivot_table.reset_index()
pivot_table['CompanyName'] = [str(x) for x in pivot_table['CompanyName']]
Companies = list(pivot_table['CompanyName'])
months = ["1","2","3","4","5","6","7","8","9","10","11","12"]
pivot_table = pivot_table.set_index('CompanyName')

and for plotting I've tried

ax = pivot_table.plot(kind='bar', title ="Bar chart",figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel("Company",fontsize=12)
ax.set_ylabel("Number of Calls",fontsize=12)

and

pivot_table.plot(kind='bar',stacked=True)

and tried to do it in bokeh (being pretty is important for this plot) with:

months = OrderedDict(Jan=Jan, Feb=Feb, Mar=Mar, Apr=Apr, 

May=May,Jun=Jun,Jul=Jul,Aug=Aug,Sep=Sep,Oct=Oct,Nov=Nov,Dec=Dec)


# any of the following commented are also alid Bar inputs
#medals = pd.DataFrame(medals)
#medals = list(medals.values())

output_file("stacked_bar.html")

bar = Bar(months, Companies, title="Stacked bars", stacked=True)

show(bar)

And for all three plotting methods, keep getting this error: ValueError: Length mismatch: Expected axis has 27 elements, new values have 3 elements I've looked up this ValueError but I still don't understand what's going on here.

就我而言,我正在读取错误的数据文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM