为柱状图添加数据

from matplotlib import pyplot as plt
import matplotlib
import pandas as pd
import numpy as np

font = {'family': 'MicroSoft YaHei',
        'weight': 'bold',
        'size': '8'}
matplotlib.rc("font", **font)

age = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75]
P_num = [372, 27, 115, 1671, 10293, 24256, 24326,
         22674, 23020, 116522, 11849, 5395, 2137, 704]

C_num = [920, 71, 232, 3604, 23134, 60621, 72797, 86879,
         99235, 63754, 43330, 12543, 3948, 1581]
print(len(age), len(P_num), len(C_num))

fig, ax = plt.subplots(1, 2, figsize=(8, 20), dpi=100, sharex=True)
bar_width = 0.5
x_1 = range(len(P_num))
# x_2 = [i + bar_width for i in x_1]
ax[0].bar(x_1, P_num)
# y_label = ["{:.1f}".format(_y) for _y in P_num]
ax[0].set_xlabel('年龄(岁)')
ax[0].set_ylabel('总人数(个)')
ax[0].set_title('不同年龄会员的数量')
x = 0
for y in P_num:
    # plt.text(x+500, y-0.2, "%s" %x)
    ax[0].text(x, y + 100, y, ha='center', va='bottom')
    x += 1
# ax[0].set_yticks(P_num)
ax[1].bar(x_1, C_num)
# ax[0].set_xlabel('年龄(岁)')
ax[1].set_ylabel('总消费次数(次)')
ax[1].set_title('不同年龄会员的购买力')
x = 0
for y in C_num:
    # plt.text(x+500, y-0.2, "%s" %x)
    ax[1].text(x, y + 1000, y, ha='center', va='bottom')
    x += 1
plt.xticks(x_1, age)

plt.show()

在这里插入图片描述
需要注意的是:
1、当plt.subplots()为以一维的时候也就是一行多列的时候,行号可以省略。要是多维的时候就需要用ax[i,j]来定位是第几行第几列。
2、在设置text的时候只能是一个柱一个柱的设置。我那个for循环写的不简洁,但是比较好理解。可以使用zip函数来简化。

发布了46 篇原创文章 · 获赞 18 · 访问量 1340

猜你喜欢

转载自blog.csdn.net/qq_44099721/article/details/104024199
今日推荐