用python的Matplotlib库画多序列条形图和堆叠条形图

多序列条形图

  • 方法一:用多个条形图的函数
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

index = np.arange(4)  
data1 = [1,5,6,3]
data2 = [1,2,3,5]
data3 = [4,8,9,4]

a = 0.3  #将一个空间分为3部分,a=0.3,3个占0.9,剩余0.1的空格
plt.title('multi bar chart')

plt.bar(index,  # 条形图所在下标
        data1, a, color = 'pink', label = 'a')
plt.bar(index+a, 
        data2, a, color = 'c', label = 'b')
plt.bar(index+2*a, 
        data3, a, color = 'orange', alpha = 0.5,label = 'c')

plt.legend()

在这里插入图片描述
同样可以画横向的多序列条形图

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

index = np.arange(4)  
data1 = [1,5,6,3]
data2 = [1,2,3,5]
data3 = [4,8,9,4]

a = 0.3  #将一个空间分为3部分,a=0.3,3个占0.9,剩余0.1的空格
plt.title('multi bar chart')

plt.barh(index,  # 条形图所在下标
        data1, a, color = 'pink', label = 'a',hatch = '/')
plt.barh(index+a, 
        data2, a, color = 'c', label = 'b')
plt.barh(index+2*a, 
        data3, a, color = 'orange', alpha = 0.5,label = 'c')

plt.legend()

在这里插入图片描述

  • 方法二:用DataFrame生成多序列条形图
import pandas as pd
%pylab inline

colors = ['pink','orange','c']
df = pd.DataFrame([[4,8,2],[1,5,3],[2,5,4]])
df.plot(kind = 'bar',color = colors)

在这里插入图片描述
同样的我们可以画横向的条形图、折线图等

import pandas as pd
%pylab inline

colors = ['pink','orange','c']
df = pd.DataFrame([[4,8,2],[1,5,3],[2,5,4]])
df.plot(kind = 'barh',color = colors)

在这里插入图片描述

堆叠条形图

由于要用到列表相加,所以我们需要ndarray的列表来进行叠加

#堆叠条形图

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

index = np.arange(4)  
data1 = np.array([1,5,6,3])
data2 = np.array([1,2,1,5])
data3 = np.array([4,8,9,4])

a = 0.3
plt.title('multi bar chart')

plt.bar(index, data1, a, color = 'pink', label = 'a', hatch = '/')
plt.bar(index, data2, a, bottom = data1,           # 堆叠在第一个上方
        color = 'c', label = 'b')
plt.bar(index, data3, a, bottom = (data1 + data2), # 堆叠在第一个和第二个上方
        color = 'orange', alpha = 0.5,label = 'c')

plt.legend()

在这里插入图片描述

同样的,横向的堆叠图改为plt.barh()
但参数bottom要改为left

#堆叠条形图

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

index = np.arange(4)  
data1 = np.array([1,5,6,3])
data2 = np.array([1,2,1,5])
data3 = np.array([4,8,9,4])

a = 0.3
plt.title('multi bar chart')

plt.barh(index, data1, a, color = 'pink', label = 'a', hatch = '/')
plt.barh(index, data2, a, left = data1,           # 堆叠在左边第一个上方
        color = 'c', label = 'b')
plt.barh(index, data3, a, left = (data1 + data2), # 堆叠在左边第一个和第二个上方
        color = 'orange', alpha = 0.5,label = 'c')

plt.legend()

在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值