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

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

技术教程推荐

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

全栈工程师修炼指南 -〔熊燚(四火)〕

NLP实战高手课 -〔王然〕

分布式金融架构课 -〔任杰〕

手把手教你玩音乐 -〔邓柯〕

说透数字化转型 -〔付晓岩〕

爆款文案修炼手册 -〔乐剑峰〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

云原生架构与GitOps实战 -〔王炜〕

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