Matplotlib条形图(Bar)

Matplotlib条形图(Bar) 首页 / Matplotlib入门教程 / Matplotlib条形图(Bar)

条形图是用高度或长度与其所代表的值成比例的矩形数据图表,条形图可以垂直或水平绘制。

Matplotlib API提供了 bar()函数,该函数可以在MATLAB样式使用以及面向对象的API中使用,如下示例-

链接:https://www.learnfk.comhttps://www.learnfk.com/matplotlib/matplotlib-bar-plot.html

来源:LearnFk无涯教程网

ax.bar(x, height, width, bottom, align)
参数说明如下
xx坐标。
height高度。
width宽度,默认为0.8。
bottom可选,y坐标默认为'None'。
align {'center','edge'},可选,默认为'center'

以下是Matplotlib条形图的简单示例。它显示了某所学院提供的各种课程的注册学生人数。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.bar(langs,students)
plt.show()
Matplotlib Bar Plot

无涯教程可以通过改变粗细和位置来绘制多个条形图。以下脚本将显示四个大条形图里面包含三个小条形图,厚度为占0.25个单位。

无涯教程网

import numpy as np
import matplotlib.pyplot as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)
Multiple Bar Charts

pyplot.bar()函数的底部可选参数允许您指定条形的起始值,第一次调用pyplot.bar()将绘制蓝色条形图,对pyplot.bar()的第二次调用绘制了红色条,蓝色条的底部在红色条的顶部。

import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
ind = np.arange(N) # the x locations for the groups
width = 0.35
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(ind, menMeans, width, color='r')
ax.bar(ind, womenMeans, width,bottom=menMeans, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0, 81, 10))
ax.legend(labels=['Men', 'Women'])
plt.show()
Scores

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

高并发系统实战课 -〔徐长龙〕

大厂设计进阶实战课 -〔小乔〕

大数据经典论文解读 -〔徐文浩〕

如何讲好一堂课 -〔薛雨〕

打造爆款短视频 -〔周维〕

代码之丑 -〔郑晔〕

Redis核心技术与实战 -〔蒋德钧〕

iOS开发高手课 -〔戴铭〕

邱岳的产品实战 -〔邱岳〕

好记忆不如烂笔头。留下您的足迹吧 :)