You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

matplotlib(pandas)绘制直方图X/Y轴配置:掷骰子模拟场景实现

解决方案

代码问题说明

你当前的实现存在两处核心问题:

  • 遗漏了matplotlib.pyplot库的导入,无法调用plt相关绘图方法
  • plt.hist()的作用是对原始离散数据自动执行频次统计,但你传入的test_data是已经统计完成的各点数出现次数数组,会导致hist最终统计的是「次数值的分布」,而非你需要的「骰子点数的分布」,完全不符合需求。

方法1:直接用hist处理原始投掷数据(推荐)

不需要提前手动统计频次,直接将所有投掷的原始结果传给hist即可,代码如下:

import random
import matplotlib.pyplot as plt

# 模拟50次投掷骰子的原始结果
n = 50
roll_results = [random.randint(1, 6) for _ in range(n)]

# 绘制直方图,bins区间设置为1-7,刚好每个区间对应一个骰子点数
plt.hist(roll_results, bins=range(1, 8), align='left', edgecolor='black')

# 设置X轴刻度为1-6的骰子点数
plt.xticks(range(1, 7))
# 设置坐标轴标签,明确X/Y轴含义
plt.xlabel('骰子点数')
plt.ylabel('出现次数')

plt.show()

参数说明:

  • bins=range(1,8):生成统计区间[1,2), [2,3) ... [6,7),刚好每个区间对应一个骰子点数
  • align='left':让柱子和左侧刻度对齐,显示效果更符合直觉
  • edgecolor='black':给柱子加黑色边框,避免相邻柱子颜色混淆

方法2:用柱状图展示已统计的频次

如果你已经提前手动统计好了每个点数的出现次数,直接用plt.bar()绘制柱状图更合适,不需要调用hist,代码如下:

import random
import matplotlib.pyplot as plt

test_data = [0, 0, 0, 0, 0, 0] 
n = 50 

for i in range(n):
  result = random.randint(1, 6)
  test_data[result - 1] = test_data[result - 1] + 1

# 绘制柱状图,X轴为1-6的点数,高度为对应点数的出现次数
plt.bar(range(1,7), test_data, edgecolor='black')

plt.xticks(range(1, 7))
plt.xlabel('骰子点数')
plt.ylabel('出现次数')

plt.show()

内容的提问来源于stack exchange,提问作者freshman_2021

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 07:24:03