柱状图
基本概念
- 柱状图是一种用矩形柱来表示数据分类的图表,既可以垂直绘制,也可以水平绘制,它的高度与其所表示的数值成正比关系
- 语法格式:matplotlib.pyplot.bar(x, height, width: float = 0.8, bottom = None, , align: str = ‘center’, data = None, *kwargs)
- 参数说明
普通柱状图
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falsedata = [5, 20, 15, 25, 20]plt.title("基本柱状图")plt.grid(ls="--", alpha=0.5)plt.bar(range(len(data)), data, ec='r', lw=2, color=['r', 'g', 'b'], bottom=[10, 20, 5, 0, 10])plt.show()
同位置多柱状图
import matplotlib.pyplot as pltimport numpy as npplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falsecountries = ['挪威', '德国', '中国', '美国', '瑞典']gold_medal = [16, 12, 9, 8, 8]silver_medal = [8, 10, 4, 10, 5]bronze_medal = [13, 5, 2, 7, 5]x_int = np.arange(len(countries))width = 0.2gold_x = x_intsilver_x = x_int + widthbronze_x = x_int + 2 * widthplt.bar(gold_x, gold_medal, width=width, color="gold", label="金牌")plt.bar(silver_x, silver_medal, width=width, color="silver", label="银牌")plt.bar(bronze_x, bronze_medal, width=width, color="saddlebrown", label="铜牌")plt.xticks(x_int + width, labels=countries)for i in range(len(countries)):plt.text(gold_x[i], gold_medal[i], gold_medal[i], va="bottom", ha="center", fontsize=8)plt.text(silver_x[i], silver_medal[i], silver_medal[i], va="bottom", ha="center", fontsize=8)plt.text(bronze_x[i], bronze_medal[i], bronze_medal[i], va="bottom", ha="center", fontsize=8)plt.legend()plt.show()
堆叠柱状图
import matplotlib.pyplot as pltimport numpy as npplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falsecountries = ['挪威', '德国', '中国', '美国', '瑞典']gold_medal = np.array([16, 12, 9, 8, 8])silver_medal = np.array([8, 10, 4, 10, 5])bronze_medal = np.array([13, 5, 2, 7, 5])width = 0.3plt.bar(countries, gold_medal, color='gold', label='金牌', bottom=silver_medal + bronze_medal, width=width)plt.bar(countries, silver_medal, color='silver', label='银牌', bottom=bronze_medal, width=width)plt.bar(countries, bronze_medal, color='#A0522D', label='铜牌', width=width)plt.ylabel('奖牌数')for i in range(len(countries)):max_y = bronze_medal[i] + silver_medal[i] + gold_medal[i]plt.text(countries[i], max_y, max_y, va='bottom', ha='center')plt.legend(loc='upper right')plt.show()
水平柱状图
调用Matplotlib的barh()函数,barh()函数的用法与bar()函数的用法基本一样,只是使用y参数传入Y轴数据,使用width参数传入条柱宽度的数据
import matplotlib.pyplot as pltimport numpy as npplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falsemovie = ['新蝙蝠侠', '狙击手', '奇迹笨小孩']real_day1 = np.array([4053, 2548, 1543])real_day2 = np.array([7840, 4013, 2421])real_day3 = np.array([8080, 3673, 1342])left_day2 = real_day1left_day3 = real_day1 + real_day2height = 0.2plt.barh(movie, real_day1, height=height)plt.barh(movie, real_day2, left=left_day2, height=height)plt.barh(movie, real_day3, left=left_day3, height=height)sum_data = real_day1 + real_day2 + real_day3# horizontalalignment(ha): 控制文本的x位置参数在文本边界框的左边,中间或右边# verticalalignment(va): 控制文本的y位置参数在文本边界框的底部,中心或顶部for i in range(len(movie)):plt.text(sum_data[i], movie[i], sum_data[i], va="center", ha="left")plt.xlim(0, sum_data.max() + 2000)plt.show()

import matplotlib.pyplot as pltimport numpy as npplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falsemovie = ['新蝙蝠侠', '狙击手', '奇迹笨小孩']real_day1 = np.array([4053, 2548, 1543])real_day2 = np.array([7840, 4013, 2421])real_day3 = np.array([8080, 3673, 1342])num_y = np.arange(len(movie))height = 0.2movie1_start_y = num_ymovie2_start_y = num_y + heightmovie3_start_y = num_y + 2 * heightplt.barh(movie1_start_y, real_day1, height=height)plt.barh(movie2_start_y, real_day2, height=height)plt.barh(movie3_start_y, real_day3, height=height)plt.yticks(num_y + height, movie)plt.show()
直方图
基本概念
- 直方图又称质量分布图,是条形图的一种,由一系列高度不等的纵向线段来表示数据分布的情况。直方图的横轴表示数据类型,纵轴表示分布情况
- 直方图用于概率分布,显示了一组数值序列在给定的数值范围内出现的概率;而柱状图则用于显示各个类别的频数

- 语法格式:nums, bins, patches = plt.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, , data=None, *kwargs)
- 参数说明
- x: 作直方图所要用的数据,必须是一维数组;多维数组可以先进行扁平化再作图;必选参数
- bins: 直方图的柱数,即要分的组数,默认为10
- weights:与x形状相同的权重数组;将x中的每个元素乘以对应权重值再计数;如果normed或density取值为True,则会对权重进行归一化处理。这个参数可用于绘制已合并的数据的直方图
- density:布尔,可选。如果”True”,返回元组的第一个元素将会将计数标准化以形成一个概率密度,也就是说,直方图下的面积(或积分)总和为1。这是通过将计数除以数字的数量来实现的观察乘以箱子的宽度而不是除以总数数量的观察。如果叠加也是“真实”的,那么柱状图被规范化为1。(替代normed)
- bottom:数组,标量值或None;每个柱子底部相对于y=0的位置。如果是标量值,则每个柱子相对于y=0向上/向下的偏移量相同。如果是数组,则根据数组元素取值移动对应的柱子;即直方图上下便宜距离
- histtype:{‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’};’bar’是传统的条形直方图;’barstacked’是堆叠的条形直方图;’step’是未填充的条形直方图,只有外边框;‘stepfilled’是有填充的直方图;当histtype取值为’step’或’stepfilled’,rwidth设置失效,即不能指定柱子之间的间隔,默认连接在一起
- align:{‘left’, ‘mid’, ‘right’};‘left’:柱子的中心位于bins的左边缘;‘mid’:柱子位于bins左右边缘之间;‘right’:柱子的中心位于bins的右边缘
- color:具体颜色,数组(元素为颜色)或None
- label:字符串(序列)或None;有多个数据集时,用label参数做标注区分
- normed: 是否将得到的直方图向量归一化,即显示占比,默认为0,不归一化;不推荐使用,建议改用density参数
- edgecolor: 直方图边框颜色
- alpha: 透明度
- 返回值
- nums:数组,表示各个区间的值
- bins:数组,表示各个区间的范围
- patches:表示各个区间的详细信息 ```python import matplotlib.pyplot as plt import numpy as np
x_value = np.random.randint(140, 181, 300) nums, bins, patches = plt.hist(x_value, bins=10, edgecolor=’white’) print(nums) print(bins) for i in patches: print(i, i.get_x())
plt.show()
‘’’ 输出: [41. 31. 32. 21. 20. 41. 29. 21. 32. 32.] [140. 144. 148. 152. 156. 160. 164. 168. 172. 176. 180.] Rectangle(xy=(140, 0), width=4, height=41, angle=0) 140.0 Rectangle(xy=(144, 0), width=4, height=31, angle=0) 144.0 Rectangle(xy=(148, 0), width=4, height=32, angle=0) 148.0 Rectangle(xy=(152, 0), width=4, height=21, angle=0) 152.0 Rectangle(xy=(156, 0), width=4, height=20, angle=0) 156.0 Rectangle(xy=(160, 0), width=4, height=41, angle=0) 160.0 Rectangle(xy=(164, 0), width=4, height=29, angle=0) 164.0 Rectangle(xy=(168, 0), width=4, height=21, angle=0) 168.0 Rectangle(xy=(172, 0), width=4, height=32, angle=0) 172.0 Rectangle(xy=(176, 0), width=4, height=32, angle=0) 176.0 ‘’’
<a name="qYbSv"></a>### 折线直方图方法:1. 首先通过pyplot.subplots()创建axes对象1. 通过axes对象调用hist()方法绘制直方图,返回直方图所需要的x, y数据1. 然后通过axes对象调用plot()绘制折线图```pythonimport matplotlib.pyplot as pltimport numpy as npx_value = np.random.randint(140, 181, 300)fig, ax = plt.subplots()nums, bins, patches = ax.hist(x_value, bins=10, edgecolor='white')ax.plot(bins[:10], nums, '--', marker="o")plt.xticks(bins_limit, rotation=45)plt.show()
多类型直方图
import matplotlib.pyplot as pltimport numpy as npplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falsefig, ax = plt.subplots(figsize=(8, 5))x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]] # 分别生成10000,5000,2000个值n_bins = 6 # 指定分组个数ax.hist(x_multi, n_bins, histtype='bar', label=list("ABC"))ax.set_title('多类型直方图')ax.legend()plt.show()
饼状图
基本概念
- 语法格式:pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None)
- 参数说明
plt.rcParams[‘font.sans-serif’] = [‘SimHei’] plt.rcParams[‘axes.unicode_minus’] = False
labels = [‘娱乐’, ‘育儿’, ‘饮食’, ‘房贷’, ‘交通’, ‘其它’] x = [200, 500, 1200, 7000, 200, 900]
plt.title(“饼图示例”) plt.pie(x, labels=labels, autopct=’%.2f%%’) plt.show()
<a name="xhzm6"></a>### 饼状图分离```pythonimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falselabels = ['娱乐', '育儿', '饮食', '房贷', '交通', '其它']x = [200, 500, 1200, 7000, 200, 900]explode = (0.03, 0.05, 0.06, 0.04, 0.08, 0.21)plt.title("饼图示例")plt.pie(x, labels=labels, autopct='%.2f%%', explode=explode)plt.show()

