0

I am trying to run a Dice roll simulation but I keep getting KeyError. The code seems ok to me but unable to figure out the issue. This program simulates rolling two dice simultaneously and counting the outcomes and plotting those frequencies using dynamic animations.

# RollDieDynamic.py
"""Dynamically graphing frequencies of die rolls."""
from matplotlib import animation
import matplotlib.pyplot as plt
import random 
import seaborn as sns
import sys

def update(frame_number, rolls, faces, die_rolls):
    """Configures bar plot contents for each animation frame."""
    # roll die and update frequencies
    die_rolls = []
    for i in range(rolls):
        frequencies = random.randint(1, 6) + random.randint(1, 6)
        die_rolls.append(frequencies)

    # reconfigure plot for updated die frequencies
    plt.cla()  # clear old contents contents of current Figure
    axes = sns.barplot(faces, die_rolls, palette='bright')  # new bars
    axes.set_title(f'Die Frequencies for {sum(die_rolls):,} Rolls')
    axes.set(xlabel='Die Value', ylabel='Frequency')  
    axes.set_ylim(top=max(die_rolls) * 1.10)  # scale y-axis by 10%

    # display frequency & percentage above each patch (bar)
    for bar, frequency in zip(axes.patches, die_rolls):
        text_x = bar.get_x() + bar.get_width() / 2.0  
        text_y = bar.get_height() 
        text = f'{frequency:,}\n{frequency / sum(die_rolls):.3%}'
        axes.text(text_x, text_y, text, ha='center', va='bottom')

# read command-line arguments for number of frames and rolls per frame
number_of_frames = int(sys.argv[1])  
rolls_per_frame = int(sys.argv[2])  

sns.set_style('whitegrid')  # white background with gray grid lines
figure = plt.figure('Rolling a Six-Sided Die')  # Figure for animation
values = list(range(1, 7))  # die faces for display on x-axis
die_rolls = [0] * 6  # six-element list of die frequencies

# configure and start animation that calls function update
die_animation = animation.FuncAnimation(
    figure, update, repeat=False, frames=number_of_frames, interval=33,
    fargs=(rolls_per_frame, values, die_rolls))

plt.show()  # display window

Here's the command I am running in Jupyter terminal. This command rolls two dice for 6000 times for 1 frame at a time.

IPython RollDieDynamic.py 6000 1

Here's the error message I keep getting in the Jupyter terminal,

Traceback (most recent call last):
  File "C:\Users\trenton\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 287, in process
    func(*args, **kwargs)
  File "C:\Users\trenton\anaconda3\lib\site-packages\matplotlib\animation.py", line 909, in _start
    self._init_draw()
  File "C:\Users\trenton\anaconda3\lib\site-packages\matplotlib\animation.py", line 1698, in _init_draw
    self._draw_frame(frame_data)
  File "C:\Users\trenton\anaconda3\lib\site-packages\matplotlib\animation.py", line 1720, in _draw_frame
    self._drawn_artists = self._func(framedata, *self._args)
  File "D:\users\trenton\Dropbox\PythonProjects\stack_overflow\RollDieDynamic.py", line 19, in update
    axes = sns.barplot(faces, die_rolls, palette='bright')  # new bars
  File "C:\Users\trenton\anaconda3\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
    return f(**kwargs)
  File "C:\Users\trenton\anaconda3\lib\site-packages\seaborn\categorical.py", line 3182, in barplot
    plotter = _BarPlotter(x, y, hue, data, order, hue_order,
  File "C:\Users\trenton\anaconda3\lib\site-packages\seaborn\categorical.py", line 1584, in __init__
    self.establish_variables(x, y, hue, data, orient,
  File "C:\Users\trenton\anaconda3\lib\site-packages\seaborn\categorical.py", line 206, in establish_variables
    plot_data, value_label = self._group_longform(vals, groups,
  File "C:\Users\trenton\anaconda3\lib\site-packages\seaborn\categorical.py", line 253, in _group_longform
    grouped_vals = vals.groupby(grouper)
  File "C:\Users\trenton\anaconda3\lib\site-packages\pandas\core\series.py", line 1922, in groupby
    return SeriesGroupBy(
  File "C:\Users\trenton\anaconda3\lib\site-packages\pandas\core\groupby\groupby.py", line 882, in __init__
    grouper, exclusions, obj = get_grouper(
  File "C:\Users\trenton\anaconda3\lib\site-packages\pandas\core\groupby\grouper.py", line 882, in get_grouper
    raise KeyError(gpr)
KeyError: 1

Any help or insight is appreciated. Thanks!

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
sqlearner
  • 67
  • 1
  • 9
  • This primary issue is, in `update`, `faces` is always `[1, 2, 3, 4, 5, 6]`, but `die_rolls` is `[frequencies]` where `frequencies` is a single number. The length of `die_rolls` does not match the length of `faces`. Presumable, the point is to plot a count of the number of times each number 1-6 is rolled, and update the bars with the animation. In order to do this animation, it would be better to use `sns.countplot` and `die_rolls` needs to accumulate numbers with each iteration of the animation, which it's not doing, – Trenton McKinney Jul 25 '22 at 17:52
  • If you do `frequencies = random.randint(1, 6) + random.randint(1, 6)` then the range on the x-axis would be 2-12, because `frequencies` is the sum of the two rolls. – Trenton McKinney Jul 25 '22 at 18:06
  • [matplotlib animation bar chart site:stackoverflow.com](https://www.google.com/search?q=matplotlib+animation+bar+chart+site:stackoverflow.com&rlz=1C1RXQR_enUS982US982&sxsrf=ALiCzsYzbbXlPzOVXFqinS-dD4MhEh_p_Q:1658779686265&sa=X&ved=2ahUKEwjK-tbv65T5AhUGFzQIHXldAvUQrQIoBHoECAoQBQ&biw=1278&bih=1327&dpr=1) – Trenton McKinney Jul 25 '22 at 20:16

0 Answers0