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

如何使用Python Pandas修改柱状图X/Y轴以展示骰子投掷统计

调整骰子投掷结果柱状图为点数频次统计样式

你当前的代码直接对每次投掷的结果绘制柱状图,导致X轴显示投掷序号而非骰子点数。要实现目标样式,需先统计每个点数的出现次数,再基于统计结果绘图,修改后的代码如下:

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

print("how many times do you want to roll the dice?")
y = input()
x = int(y)

# 生成投掷结果
df = pd.DataFrame(np.random.randint(1,7, size=(x, 1)))
df.index += 1

heads = ["Roll number", "Dice number"]
print(tabulate(df, headers=heads, tablefmt="fancy_grid"))

# 统计每个点数的出现次数,并按1-6的顺序排序
counts = df[0].value_counts().sort_index()

# 绘制目标柱状图
bg = counts.plot.bar(fontsize='9', title='骰子点数投掷频次')
bg.set_xlabel('骰子点数')
bg.set_ylabel('投掷次数')

plt.show()

关键修改说明:

  • 用df[0].value_counts()统计每个点数的出现次数,返回结果的键为点数、值为对应投掷次数
  • 调用sort_index()确保点数按1到6的顺序排列,避免X轴顺序混乱
  • 通过set_xlabel和set_ylabel设置坐标轴标签,明确图表含义
  • 移除stacked=True参数,堆叠柱状图不适用于单系列的频次统计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:17:03