背景案例:可视化展示两个骰子点数相乘的结果
die.py
from random import randint
class Die():def __init__(self,num_sides=6):self.num_sides = num_sidesdef roll(self):return randint(1,self.num_sides)
die_visual.py
from die import Die
from matplotlib import pyplot as pltdie_1 = Die()
die_2 = Die()results = []
for roll_num in range(1000):result = die_1.roll() * die_2.roll()results.append(result)frequences = []
max_result = die_1.num_sides * die_2.num_sides
for value in range(1,max_result+1):frequence = results.count(value)frequences.append(frequence)# 未转换前
# plt.bar(range(1,max_result+1),frequences)
# plt.show()# 转换后
x = [str(i) for i in range(1,max_result+1)]
plt.bar(x,frequences)
plt.xticks(rotation = 45)plt.show()
解决方法:
把x轴int类型转换为字符串类型再放入列表中。
结果图对比: