前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python数据处理从零开始----第四章(可视化)①②堆积柱状图目录使用Matplotlib和Pandas轻松堆积图表

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

作者头像
用户1359560
发布2018-12-21 16:47:09
2.2K0
发布2018-12-21 16:47:09
举报
文章被收录于专栏:生信小驿站

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

使用Matplotlib和Pandas轻松堆积图表

  • 为何要绘制堆积图表

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

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

  • 绘制只有两个图层的叠加图
代码语言:javascript
复制
# -*- 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列作为每个月的高度。

代码语言:javascript
复制
# 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函数。最终结果是一个新的数据框。

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.12.01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用Matplotlib和Pandas轻松堆积图表
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档