python百分比堆积条形图_Python数据处理从零开始----第四章(可视化)①②堆积柱状图...

目录

Python数据处理从零开始----第四章(可视化)①②堆积柱状图

===============================================

使用Matplotlib和Pandas轻松堆积图表

为何要绘制堆积图表

因为堆积图标可以表示多个变量或者分组内部的构成比

但是一般情况下使用Matplotlib创建堆积条形图可能很困难。因为堆叠图需要的数据不是典型的行列dataframe,经典的数据框行为观测值,列为属性,而需要绘制堆积图表时是其他形式,甚至可能不是数据框而是多个series。

绘制只有两个图层的叠加图

# -*- coding: utf-8 -*-

"""

Created on Sat Dec 1 03:03:23 2018

@author: czh

"""

%clear

%reset -f

# In[*]

import numpy as np

import matplotlib.pyplot as plt

# In[*]

N = 5

menMeans = (20, 35, 30, 35, 27)

womenMeans = (25, 32, 34, 20, 25)

menStd = (2, 3, 4, 1, 2)

womenStd = (3, 5, 2, 3, 3)

ind = np.arange(N) # the x locations for the groups

width = 0.35 # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, yerr=menStd)

p2 = plt.bar(ind, womenMeans, width,

bottom=menMeans, yerr=womenStd)

plt.ylabel('Scores')

plt.title('Scores by group and gender')

plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))

plt.yticks(np.arange(0, 81, 10))

plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

74d878528d60

绘制三个图层的叠加图

下面是一个示例数据框,数据以列为单位。 在这种情况下,我们要创建一个堆积图,使用Year列作为x轴刻度线,Month列作为图层,Value列作为每个月的高度。

# In[*]

%matplotlib inline

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import matplotlib

data = [[2000, 2000, 2000, 2001, 2001, 2001, 2002, 2002, 2002],

['Jan', 'Feb', 'Mar', 'Jan', 'Feb', 'Mar', 'Jan', 'Feb', 'Mar'],

[1, 2, 3, 4, 5, 6, 7, 8, 9]]

rows = list(zip(data[0], data[1], data[2]))

headers = ['Year', 'Month', 'Value']

df = pd.DataFrame(rows, columns=headers)

df

# In[*]

fig, ax = plt.subplots(figsize=(10,7))

months = df['Month'].drop_duplicates()

margin_bottom = np.zeros(len(df['Year'].drop_duplicates()))

colors = ["#006D2C", "#31A354","#74C476"]

for num, month in enumerate(months):

values = list(df[df['Month'] == month].loc[:, 'Value'])

df[df['Month'] == month].plot.bar(x='Year',y='Value', ax=ax, stacked=True,

bottom = margin_bottom, color=colors[num], label=month)

margin_bottom += values

plt.show()

74d878528d60

使用Pivot

虽然上述方法效果很好,但必须有更好的方法。在这里Pandas可能更好的解决该问题里。pivot函数接受索引的参数(x轴和Y轴),类似于R语言中的整理转置reshape或者cast函数。最终结果是一个新的数据框。

pivot_df = df.pivot(index='Year', columns='Month', values='Value')

pivot_df

#Note: .loc[:,['Jan','Feb', 'Mar']] is used here to rearrange the layer ordering

pivot_df.loc[:,['Jan','Feb', 'Mar']].plot.bar(stacked=True, color=colors, figsize=(10,7))

74d878528d60

image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值