柱状图

基本概念

  • 柱状图是一种用矩形柱来表示数据分类的图表,既可以垂直绘制,也可以水平绘制,它的高度与其所表示的数值成正比关系
  • 语法格式:matplotlib.pyplot.bar(x, height, width: float = 0.8, bottom = None, , align: str = ‘center’, data = None, *kwargs)
  • 参数说明

image.png

普通柱状图

  1. import matplotlib.pyplot as plt
  2. plt.rcParams['font.sans-serif'] = ['SimHei']
  3. plt.rcParams['axes.unicode_minus'] = False
  4. data = [5, 20, 15, 25, 20]
  5. plt.title("基本柱状图")
  6. plt.grid(ls="--", alpha=0.5)
  7. plt.bar(range(len(data)), data, ec='r', lw=2, color=['r', 'g', 'b'], bottom=[10, 20, 5, 0, 10])
  8. plt.show()

image.png

同位置多柱状图

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.rcParams['font.sans-serif'] = ['SimHei']
  4. plt.rcParams['axes.unicode_minus'] = False
  5. countries = ['挪威', '德国', '中国', '美国', '瑞典']
  6. gold_medal = [16, 12, 9, 8, 8]
  7. silver_medal = [8, 10, 4, 10, 5]
  8. bronze_medal = [13, 5, 2, 7, 5]
  9. x_int = np.arange(len(countries))
  10. width = 0.2
  11. gold_x = x_int
  12. silver_x = x_int + width
  13. bronze_x = x_int + 2 * width
  14. plt.bar(gold_x, gold_medal, width=width, color="gold", label="金牌")
  15. plt.bar(silver_x, silver_medal, width=width, color="silver", label="银牌")
  16. plt.bar(bronze_x, bronze_medal, width=width, color="saddlebrown", label="铜牌")
  17. plt.xticks(x_int + width, labels=countries)
  18. for i in range(len(countries)):
  19. plt.text(gold_x[i], gold_medal[i], gold_medal[i], va="bottom", ha="center", fontsize=8)
  20. plt.text(silver_x[i], silver_medal[i], silver_medal[i], va="bottom", ha="center", fontsize=8)
  21. plt.text(bronze_x[i], bronze_medal[i], bronze_medal[i], va="bottom", ha="center", fontsize=8)
  22. plt.legend()
  23. plt.show()

image.png

堆叠柱状图

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.rcParams['font.sans-serif'] = ['SimHei']
  4. plt.rcParams['axes.unicode_minus'] = False
  5. countries = ['挪威', '德国', '中国', '美国', '瑞典']
  6. gold_medal = np.array([16, 12, 9, 8, 8])
  7. silver_medal = np.array([8, 10, 4, 10, 5])
  8. bronze_medal = np.array([13, 5, 2, 7, 5])
  9. width = 0.3
  10. plt.bar(countries, gold_medal, color='gold', label='金牌', bottom=silver_medal + bronze_medal, width=width)
  11. plt.bar(countries, silver_medal, color='silver', label='银牌', bottom=bronze_medal, width=width)
  12. plt.bar(countries, bronze_medal, color='#A0522D', label='铜牌', width=width)
  13. plt.ylabel('奖牌数')
  14. for i in range(len(countries)):
  15. max_y = bronze_medal[i] + silver_medal[i] + gold_medal[i]
  16. plt.text(countries[i], max_y, max_y, va='bottom', ha='center')
  17. plt.legend(loc='upper right')
  18. plt.show()

image.png

水平柱状图

调用Matplotlib的barh()函数,barh()函数的用法与bar()函数的用法基本一样,只是使用y参数传入Y轴数据,使用width参数传入条柱宽度的数据

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.rcParams['font.sans-serif'] = ['SimHei']
  4. plt.rcParams['axes.unicode_minus'] = False
  5. movie = ['新蝙蝠侠', '狙击手', '奇迹笨小孩']
  6. real_day1 = np.array([4053, 2548, 1543])
  7. real_day2 = np.array([7840, 4013, 2421])
  8. real_day3 = np.array([8080, 3673, 1342])
  9. left_day2 = real_day1
  10. left_day3 = real_day1 + real_day2
  11. height = 0.2
  12. plt.barh(movie, real_day1, height=height)
  13. plt.barh(movie, real_day2, left=left_day2, height=height)
  14. plt.barh(movie, real_day3, left=left_day3, height=height)
  15. sum_data = real_day1 + real_day2 + real_day3
  16. # horizontalalignment(ha): 控制文本的x位置参数在文本边界框的左边,中间或右边
  17. # verticalalignment(va): 控制文本的y位置参数在文本边界框的底部,中心或顶部
  18. for i in range(len(movie)):
  19. plt.text(sum_data[i], movie[i], sum_data[i], va="center", ha="left")
  20. plt.xlim(0, sum_data.max() + 2000)
  21. plt.show()

image.png

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.rcParams['font.sans-serif'] = ['SimHei']
  4. plt.rcParams['axes.unicode_minus'] = False
  5. movie = ['新蝙蝠侠', '狙击手', '奇迹笨小孩']
  6. real_day1 = np.array([4053, 2548, 1543])
  7. real_day2 = np.array([7840, 4013, 2421])
  8. real_day3 = np.array([8080, 3673, 1342])
  9. num_y = np.arange(len(movie))
  10. height = 0.2
  11. movie1_start_y = num_y
  12. movie2_start_y = num_y + height
  13. movie3_start_y = num_y + 2 * height
  14. plt.barh(movie1_start_y, real_day1, height=height)
  15. plt.barh(movie2_start_y, real_day2, height=height)
  16. plt.barh(movie3_start_y, real_day3, height=height)
  17. plt.yticks(num_y + height, movie)
  18. plt.show()

image.png

直方图

基本概念

  • 直方图又称质量分布图,是条形图的一种,由一系列高度不等的纵向线段来表示数据分布的情况。直方图的横轴表示数据类型,纵轴表示分布情况
  • 直方图用于概率分布,显示了一组数值序列在给定的数值范围内出现的概率;而柱状图则用于显示各个类别的频数

image.png

  • 语法格式: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 ‘’’

  1. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/12692524/1657119602316-df7b7051-e7c7-47ec-9886-2e84ca373509.png#clientId=uebd652c9-c0c5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=311&id=uf2dd74ae&margin=%5Bobject%20Object%5D&name=image.png&originHeight=466&originWidth=628&originalType=binary&ratio=1&rotation=0&showTitle=false&size=15134&status=done&style=none&taskId=u462754e2-d367-4431-9a83-46721fa2669&title=&width=418.6666666666667)
  2. <a name="qYbSv"></a>
  3. ### 折线直方图
  4. 方法:
  5. 1. 首先通过pyplot.subplots()创建axes对象
  6. 1. 通过axes对象调用hist()方法绘制直方图,返回直方图所需要的x, y数据
  7. 1. 然后通过axes对象调用plot()绘制折线图
  8. ```python
  9. import matplotlib.pyplot as plt
  10. import numpy as np
  11. x_value = np.random.randint(140, 181, 300)
  12. fig, ax = plt.subplots()
  13. nums, bins, patches = ax.hist(x_value, bins=10, edgecolor='white')
  14. ax.plot(bins[:10], nums, '--', marker="o")
  15. plt.xticks(bins_limit, rotation=45)
  16. plt.show()

image.png

多类型直方图

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.rcParams['font.sans-serif'] = ['SimHei']
  4. plt.rcParams['axes.unicode_minus'] = False
  5. fig, ax = plt.subplots(figsize=(8, 5))
  6. x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]] # 分别生成10000,5000,2000个值
  7. n_bins = 6 # 指定分组个数
  8. ax.hist(x_multi, n_bins, histtype='bar', label=list("ABC"))
  9. ax.set_title('多类型直方图')
  10. ax.legend()
  11. plt.show()

image.png

饼状图

基本概念

  • 语法格式:pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None)
  • 参数说明
    • x: 数组序列,数组元素对应扇形区域的数量大小
    • labels: 列表字符串序列,为每个扇形区域备注一个标签名字
    • colors; 为每个扇形区域设置颜色,默认按照颜色周期自动设置
    • autopct: 格式化字符串”fmt%pct”,使用百分比的格式设置每个扇形区的标签,并将其放置在扇形区内
    • pctdistance:设置百分比标签与圆心的距离
    • labeldistance:设置各扇形标签(图例)与圆心的距离
    • explode: 指定饼图某些部分的突出显示,即呈现爆炸式
    • shadow:是否添加饼图的阴影效果

      百分比显示

      ```python import matplotlib.pyplot as plt

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()

  1. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/12692524/1657154652541-fc770037-0596-4f57-98aa-d1e65bc88ff3.png#clientId=ub51eb240-4534-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=278&id=ue4eedba5&margin=%5Bobject%20Object%5D&name=image.png&originHeight=417&originWidth=433&originalType=binary&ratio=1&rotation=0&showTitle=false&size=35729&status=done&style=none&taskId=u465a64e6-2a6e-4bc2-a67c-601b7413652&title=&width=288.6666666666667)
  2. <a name="xhzm6"></a>
  3. ### 饼状图分离
  4. ```python
  5. import matplotlib.pyplot as plt
  6. plt.rcParams['font.sans-serif'] = ['SimHei']
  7. plt.rcParams['axes.unicode_minus'] = False
  8. labels = ['娱乐', '育儿', '饮食', '房贷', '交通', '其它']
  9. x = [200, 500, 1200, 7000, 200, 900]
  10. explode = (0.03, 0.05, 0.06, 0.04, 0.08, 0.21)
  11. plt.title("饼图示例")
  12. plt.pie(x, labels=labels, autopct='%.2f%%', explode=explode)
  13. plt.show()

image.png