06 Python Matplotlib library to draw histogram

Draw a vertical histogram

x = [1980, 1985, 1990, 1995]
x_labels = ['1980年', '1985年', '1990年', '1995年']
y = [1000, 3000, 4000, 5000]

plt.bar(x, y, width = 1) # width修改柱的宽度
plt.rcParams['font.sans-serif'] = ['SimHei'] # 正常显示中文标签
plt.xticks(x, x_labels) # 修改x轴的值

Add callout

plt.xlabel('年份')
plt.ylabel('销量')
plt.title('根据年份销量对比图')
plt.show()

effect:

Insert picture description here

Draw a horizontal histogram

np.random.seed(10)
x = np.arange(5)
y = np.random.randint(0, 13, 5)
print(x, y)

plt.subplot(1, 2, 1)                              # 将画布分成一行两列
v_bar = plt.bar(x, y)
plt.rcParams['font.sans-serif'] = ['SimHei']      # 正常显示中文标签
plt.axhline(0, color = 'blue', linewidth = 2)     # 在横向添加线条
# barh 将 y 和 x 轴对换,纵向为 x 轴, 横向为 y 轴
plt.subplot(1, 2, 2)
h_bar = plt.barh(x, y, color = 'red')

# 在第二列的画布中0位置处画蓝色的线
plt.axvline(0, color = 'red', linewidth = 2)      #在垂直方向添加线条
plt.show()

Set up different colored columns

np.random.seed(10)
x = np.arange(5)
y = np.random.randint(-5, 13, 5)
print(x, y)
v_bar = plt.bar(x, y, color = 'blue')

# 对 y 轴大于0 设置为蓝色,小于0的柱设置为绿色
for bar, height in zip(v_bar, y):
    if height < 0:
      bar.set(color = 'green')

plt.show()

Small example of histogram

# 创建电影名称
Mov_name = ['A', 'B', 'C', 'D', 'E', 'F'] 

# 创建随机票房数量
num1 = []                                 
num2 = []
num3 = []
num4 = []
num5 = []
num6 = []
for i in range(6):
    a = np.random.randint(2000,8000)
    for j in num1, num2, num3, num4, num5, num6:
        j.append(a + np.random.randint(-1300, 1500))
##print(num1,num2,num3,num4,num5,num6)
x = np.arange(len(Mov_name))

# 绘制柱状图
wid = 0.13
plt.bar(x, num1, alpha = 0.5, width = wid, label = Mov_name[0])
plt.bar([i + wid   for i in x], num2, alpha = 0.5, width = wid, label = Mov_name[1])
plt.bar([i + wid*2 for i in x], num3, alpha = 0.5, width = wid, label = Mov_name[2])
plt.bar([i + wid*3 for i in x], num4, alpha = 0.5, width = wid, label = Mov_name[3])
plt.bar([i + wid*4 for i in x], num5, alpha = 0.5, width = wid, label = Mov_name[4])
plt.bar([i + wid*5 for i in x], num6, alpha = 0.5, width = wid, label = Mov_name[5])

#设置x 坐标的值 第1天 第2天 ···
plt.rcParams['font.sans-serif'] = ['SimHei']  # 正常显示中文标签
x_label = ['第{}天'.format(i + 1) for i in x] # x 轴标注
plt.xticks([i + wid*2.5 for i in x],x_label)

plt.legend()                                  # 添加图例


plt.ylabel('票房($美元)')
plt.xlabel('上映天数')
plt.title('6部电影上映前六天每天票房收入')

plt.show()

Output result:

Insert picture description here

Published 36 original articles · praised 0 · visits 625

Guess you like

Origin blog.csdn.net/Corollary/article/details/105398050