Python数据处理从零开始----第四章(可视化)①②堆积柱状图目录使用Matplotlib和Pandas轻松堆积图表

时间:2022-06-16
本文章向大家介绍Python数据处理从零开始----第四章(可视化)①②堆积柱状图目录使用Matplotlib和Pandas轻松堆积图表,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

使用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()
  • 绘制三个图层的叠加图

下面是一个示例数据框,数据以列为单位。 在这种情况下,我们要创建一个堆积图,使用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()
  • 使用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))

image.png