Matplotlib - 条形图(二)

在条形图上绘制误差棒

首先,导入工具包,执行魔法指令,构造变量 data 以及误差 variance

import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

data = np.arange(1,6)
variance = np.random.random_sample(5)
data, variance

构造结果:

(array([1, 2, 3, 4, 5]),
 array([0.28817032, 0.16589511, 0.79035515, 0.14674316, 0.6107943 ]))

定义 x 轴刻度及标签:

bar_label = ['bar1','bar2','bar3','bar4','bar5']
x_pos = np.arange(len(bar_label))
x_pos

x 轴刻度 x_pos 如下:

array([0, 1, 2, 3, 4])

bar 方法绘图时,只需要使用 yerr 关键字参数传入误差,即可绘制误差棒:

plt.bar(x_pos,data,yerr=variance)
plt.ylabel('variables')
plt.xticks(x_pos,bar_label)

其中,plt.xticks 用于设定 x 轴刻度及标签。绘图结果如下:

barh 条形图

条形图除了可以纵向绘制,还可以使用 barh 横向来绘制。首先,构造两组数据,分别用于绘制两组条形图:

x1 = np.random.randint(1,5,3)
x2 = np.random.randint(-5,-1,3)

x1,x2

构造结果:

(array([4, 4, 3]), array([-5, -4, -3]))

其中,x1 中的数全为正数,x2 中的数全为负数。下面,分别将两组数据以横向条形图的形式绘制在一张图中:

y_pos = np.arange(len(x1))
bar_labels = ['bar1','bar2','bar3']

plt.figure(figsize = (8,6))
plt.barh(y_pos,x1,color='g',alpha=0.4)
plt.barh(y_pos,x2,color='r',alpha=0.4)
plt.yticks(y_pos, bar_labels)

绘制结果:

绘制包含多组数据的柱形图

绘制包含多组数据的柱形图,并方便对比每组数据中同一指标的大小。首先,构造三组数据:

green_data = np.random.randint(1,7,5)
blue_data = np.random.randint(2,8,5)
red_data = np.random.randint(3,9,5)
labels = ['A','B','C']

green_data, blue_data, red_data

构造结果:

(array([3, 1, 1, 1, 5]), array([6, 4, 7, 4, 5]), array([6, 3, 3, 3, 5]))

绘制直方图:

pos = np.arange(len(green_data)) 
width = 0.2 
alpha = 0.4
fig, ax = plt.subplots(figsize=(8,6))

plt.bar(pos,green_data,width,alpha=alpha,color='g',label=labels[0])
plt.bar(pos+width,blue_data,width,alpha=alpha,color='b',label=labels[1])
plt.bar(pos+width*2,red_data,width,alpha=alpha,color='r',label=labels[2])

绘制结果:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容