一图胜千言,使用Python的matplotlib库,可以快速创建高质量的图形。
我们团队推出一个新的系列教程:Python数据可视化,针对初级和中级用户,将理论和示例代码相结合,分别使用matplotlib, seaborn, plotly等工具实现可视化。
本文主题是如何用Matplotlib创建柱状图。
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use("ggplot")
1. 基础柱状图
柱状图(bar chart): 用长方形(柱子)的长度表示数值的统计图表,又称为条形图。柱状图常用来对比两个以上的数值,适用于较小的数据集。
Matplotlib创建柱状图的接口: b a r ( x , h e i g h t , w i d t h , b o t t o m , a l i g n , c o l o r ) bar(x, height, width, bottom, align, color) bar(x,height,width,bottom,align,color)
- x: 柱子的x轴坐标
- height: 柱子高度,y轴坐标
- width: 柱子宽度,默认0.8
- bottom: 柱子底部的y轴坐标,默认为0
- align: 柱子与x轴坐标的对齐方式,默认’center’
- color: 柱子颜色
- orientation: 柱子方向,‘horizontal’ or ‘vertical’
bar()默认创建垂直柱状图,barh()可创建水平柱状图,原理基本一致。
# 虚拟数据
x = ["A", "B", "C", "D", "E", "F", "G", "H"]
y = [150</