0% found this document useful (0 votes)
47 views

Python Crash Course by Ehmatthes 15

The document describes creating visualizations of dice roll simulations using Matplotlib and Pygal. It provides instructions on plotting random walks, histograms of single and multiple dice rolls, and increasing the complexity and size of the simulations. Key steps include generating random step values, tracking x and y coordinates, setting plot features like titles and labels, and saving figures.

Uploaded by

alfonsofdez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Python Crash Course by Ehmatthes 15

The document describes creating visualizations of dice roll simulations using Matplotlib and Pygal. It provides instructions on plotting random walks, histograms of single and multiple dice rolls, and increasing the complexity and size of the simulations. Key steps include generating random step values, tracking x and y coordinates, setting plot features like titles and labels, and saving figures.

Uploaded by

alfonsofdez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

!

"#$%&'()*+$'(%,)+-
!"#$%&'"#()$&(*+,-$.(/&0#-(/$%&#"(12#,("34,4$.56()&$7(8$(9,0&'-(*&"##:

!"#$%&'"#()$&(*+"(#"'$,-("-.*.$,(/&"(+"&"0(12-(3$4"(*$(5,$6(6+/*(7$%(*+.,5(/8$%*(97*+$,
:&/#+(:$%&#";(<3"/#"('$,#.-"&(*/5.,=(/(8&.")(#%&4"70(1)(7$%2-(3.5"(*$(5,$6(6+",(/--.*.$,/3
&"#$%&'"#(/&"(/4/.3/83">(7$%('/,(#.=,(%<()$&("?/.3(,$*.@'/*.$,#(+"&"0

!"#$%&"'()*)+,-.%/0)12
!"#!$%&'()*
!"#+$%&,-,.)/%&'()*
!"#0$%1,-)2'-3.%1,45,6
!"#"$%7)8324,.569
!"#:$%;'4,<3452%=3()-*
!"#>$%?@,%AB*
!"#B$%?C.))%A52)
!"#D$%1'-45E-52345,6

F32G%4,%*,-'45,6*H

!"#!$%&'()*
;%6'<().%.35*)/%4,%4C)%4C5./%E,@).%5*%3%!"#$H%I-,4%4C)%J.*4%JK)%2'(52%6'<().*L%36/%4C)6%E-,4%4C)
J.*4%"MMM%2'(52%6'<().*H

I-,44569%"%2'()*$

from matplotlib import pyplot as plt

# Define data.
x_values = [1, 2, 3, 4, 5]
cubes = [1, 8, 27, 64, 125]

# Make plot.
plt.scatter(x_values, cubes, edgecolor='none', s=40)

# Customize plot.
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)

# Show plot.
plt.show()

N'4E'4$

I-,44569%"MMM%2'()*$

from matplotlib import pyplot as plt

# Define data.
x_values = list(range(5001))
cubes = [x**3 for x in x_values]

# Make plot.
plt.scatter(x_values, cubes, edgecolor='none', s=40)

# Customize plot.
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.axis([0, 5100, 0, 5100**3])

# Show plot.
plt.show()

N'4E'4$

4,E

!"#+$%&,-,.)/%&'()*
;EE-O%3%2,-,.<3E%4,%O,'.%2'()*%E-,4H

from matplotlib import pyplot as plt

# Define data.
x_values = list(range(5001))
cubes = [x**3 for x in x_values]

# Make plot.
plt.scatter(x_values, cubes, edgecolor='none', c=cubes, cmap=plt.cm.BuGn, s=40)

# Customize plot.
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.axis([0, 5100, 0, 5100**3])

# Show plot.
plt.show()

N'4E'4$

4,E

!"#0$%1,-)2'-3.%1,45,6
1,/58O%%&'()*"+,-./%(O%.)E-32569% plt.scatter() %@54C% plt.plot() H%4,%*5<'-34)%4C)%E34C%,8%3%E,--)6
9.356%,6%4C)%*'.832)%,8%3%/.,E%,8%@34).L%E3**%56%4C)% rw.x_values %36/% rw.y_values L%36/%562-'/)%3
linewidth %3.9'<)64H%P*)%"MMM%56*4)3/%,8%"MLMMM%E,564*H

import matplotlib.pyplot as plt

from random_walk import RandomWalk

# Keep making new walks, as long as the program is active.


while True:
# Make a random walk, and plot the points.
rw = RandomWalk(5000)
rw.fill_walk()

# Set the size of the plotting window.


plt.figure(dpi=128, figsize=(10, 6))

point_numbers = list(range(rw.num_points))
plt.plot(rw.x_values, rw.y_values, linewidth=1)

# Emphasize the first and last points.


plt.scatter(0, 0, c='green', edgecolors='none', s=75)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',
s=75)

# Remove the axes.


plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

plt.show()

keep_running = input("Make another walk? (y/n): ")


if keep_running == 'n':
break

N'4E'4$

?C)%*2344).%E-,4*%3EE)3.%()C56/%4C)%-56)*H%?,%E-32)%4C)<%,6%4,E%,8%4C)%-56)*L%@)%236%'*)%4C)% zorder
3.9'<)64H%I-,4%)-)<)64*%@54C%C59C).% zorder %K3-')*%3.)%E-32)/%,6%4,E%,8%)-)<)64*%@54C%-,@).
zorder %K3-')*H

import matplotlib.pyplot as plt

from random_walk import RandomWalk

# Keep making new walks, as long as the program is active.


while True:
# Make a random walk, and plot the points.
rw = RandomWalk(5000)
rw.fill_walk()

# Set the size of the plotting window.


plt.figure(dpi=128, figsize=(10, 6))

point_numbers = list(range(rw.num_points))
plt.plot(rw.x_values, rw.y_values, linewidth=1, zorder=1)

# Emphasize the first and last points.


plt.scatter(0, 0, c='green', edgecolors='none', s=75, zorder=2)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',
s=75, zorder=2)

# Remove the axes.


plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

plt.show()

keep_running = input("Make another walk? (y/n): ")


if keep_running == 'n':
break

N'4E'4$

4,E

!"#"$%7)8324,.569
?C)%<)4C,/% fill_walk() %5*%-)694COH%&.)34)%3%6)@%<)4C,/%23--)/% get_step() %4,%/)4).<56)%4C)
/5.)245,6%36/%/5*4362)%8,.%)32C%*4)EL%36/%4C)6%23-2'-34)%4C)%*4)EH%Q,'%*C,'-/%)6/%'E%@54C%4@,%23--*
4,% get_step() %56% fill_walk() $

x_step = get_step()
y_step = get_step()

?C5*%.)8324,.569%*C,'-/%.)/'2)%4C)%*5R)%,8% fill_walk() %36/%<3G)%4C)%<)4C,/%)3*5).%4,%.)3/%36/


'6/).*436/H

%+0123'&+,4-./5

from random import choice

class RandomWalk():
"""A class to generate random walks."""

def __init__(self, num_points=5000):


"""Initialize attributes of a walk."""
self.num_points = num_points

# All walks start at (0, 0).


self.x_values = [0]
self.y_values = [0]

def get_step(self):
"""Determine the direction and distance for a step."""
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
step = direction * distance
return step

def fill_walk(self):
"""Calculate all the points in the walk."""

# Keep taking steps until the walk reaches the desired length.
while len(self.x_values) < self.num_points:

# Decide which direction to go, and how far to go in that direction.


x_step = self.get_step()
y_step = self.get_step()

# Reject moves that go nowhere.


if x_step == 0 and y_step == 0:
continue

# Calculate the next x and y values.


next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step

self.x_values.append(next_x)
self.y_values.append(next_y)

N'4E'4$

4,E

!"#:$%;'4,<3452%=3()-*
1,/58O%1)$-./%36/%1)!$'()*"+,-./%(O%.)E-32569%4C)%-5*4%@)%'*)/%4,%*)4%4C)%K3-')%,8% hist.x_labels %@54C
3%-,,E%4,%9)6).34)%4C5*%-5*4%3'4,<34523--OH%S8%O,'T.)%2,<8,.43(-)%@54C%-5*4%2,<E.)C)6*5,6*L%4.O
.)E-32569%4C)%,4C).% for %-,,E*%56%1)$'()*"+,-./%36/%1)!$'()*"+,-./%@54C%2,<E.)C)6*5,6*%3*%@)--H

!"#$%678)*6*82",16*+/6926321):/61)$'()*"+,-./;602961)$-./-678)*6&),,6#$6!2%%$!9$16)06:"9"%$6.%)09)0<*-

1)$'()*"+,-./5

import pygal

from die import Die

# Create a D6.
die = Die()

# Make some rolls, and store results in a list.


results = [die.roll() for roll_num in range(1000)]

# Analyze the results.


frequencies = [results.count(value) for value in range(1, die.num_sides+1)]

# Visualize the results.


hist = pygal.Bar()

hist.title = "Results of rolling one D6 1000 times."


hist.x_labels = [str(x) for x in range(1, die.num_sides+1)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6', frequencies)
hist.render_to_file('die_visual.svg')

1)!$'()*"+,-./5

import pygal

from die import Die

# Create two D6 dice.


die_1 = Die()
die_2 = Die()

# Make some rolls, and store results in a list.


results = [die_1.roll() + die_2.roll() for roll_num in range(1000)]

# Analyze the results.


max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(value) for value in range(2, max_result+1)]

# Visualize the results.


hist = pygal.Bar()

hist.title = "Results of rolling two D6 dice 1000 times."


hist.x_labels = [str(x) for x in range(2, max_result+1)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6 + D6', frequencies)


hist.render_to_file('dice_visual.svg')

4,E

!"#>$%?@,%AB*
&.)34)%3%*5<'-345,6%*C,@569%@C34%C3EE)6*%58%O,'%.,--%4@,%)59C4#*5/)/%/52)%!MMM%45<)*H%S62.)3*)%4C)
6'<().%,8%.,--*%9.3/'3--O%'645-%O,'%*43.4%4,%*))%4C)%-5<54*%,8%O,'.%*O*4)<T*%23E3(5-545)*H

import pygal

from die import Die

# Create two D8 dice.


die_1 = Die(8)
die_2 = Die(8)

# Make some rolls, and store results in a list.


results = []
for roll_num in range(1000000):
result = die_1.roll() + die_2.roll()
results.append(result)

# Analyze the results.


frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result+1):
frequency = results.count(value)
frequencies.append(frequency)

# Visualize the results.


hist = pygal.Bar()

hist.title = "Results of rolling two D8 dice 1,000,000 times."


hist.x_labels = [str(x) for x in range(2, max_result+1)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D8 + D8', frequencies)


hist.render_to_file('dice_visual.svg')

U,4)$%?C5*%*,-'45,6%,6-O%'*)*%3%-5*4%2,<E.)C)6*5,6%8,.%4C)% hist.x_labels %E3.3<)4).H%Q,'%<59C4


@364%4,%4.O%.)E-32569%4C)%,4C).%-,,E*%@54C%2,<E.)C)6*5,6*%3*%@)--H

N'4E'4$

4,E

!"#B$%?C.))%A52)
S8%O,'%.,--%4C.))%A:%/52)L%4C)%*<3--)*4%6'<().%O,'%236%.,--%5*%0%36/%4C)%-3.9)*4%6'<().%5*%!BH%&.)34)
3%K5*'3-5R345,6%4C34%*C,@*%@C34%C3EE)6*%@C)6%O,'%.,--%4C.))%A:%/52)H

import pygal

from die import Die

# Create three D6 dice.


die_1 = Die()
die_2 = Die()
die_3 = Die()

# Make some rolls, and store results in a list.


results = []
for roll_num in range(1000000):
result = die_1.roll() + die_2.roll() + die_3.roll()
results.append(result)

# Analyze the results.


frequencies = []
max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides
for value in range(3, max_result+1):
frequency = results.count(value)
frequencies.append(frequency)

# Visualize the results.


hist = pygal.Bar()

hist.title = "Results of rolling three D6 dice 1,000,000 times."


hist.x_labels = [str(x) for x in range(3, max_result+1)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6 + D6 + D6', frequencies)


hist.render_to_file('dice_visual.svg')

U,4)$%?C5*%*,-'45,6%,6-O%'*)*%3%-5*4%2,<E.)C)6*5,6%8,.%4C)% hist.x_labels %E3.3<)4).H%Q,'%<59C4


@364%4,%4.O%.)E-32569%4C)%,4C).%-,,E*%@54C%2,<E.)C)6*5,6*%3*%@)--H

N'4E'4$

4,E

!"#D$%1'-45E-52345,6
VC)6%O,'%.,--%4@,%/52)L%O,'%'*'3--O%3//%4C)%4@,%6'<().*%4,9)4C).%4,%9)4%4C)%.)*'-4H%&.)34)%3
K5*'3-5R345,6%4C34%*C,@*%@C34%C3EE)6*%58%O,'%<'-45E-O%4C)*)%6'<().*%56*4)3/H

import pygal

from die import Die

# Create two D6 dice.


die_1 = Die()
die_2 = Die()

# Make some rolls, and store results in a list.


results = []
for roll_num in range(1000000):
result = die_1.roll() * die_2.roll()
results.append(result)

# Analyze the results.


frequencies = []
max_result = die_1.num_sides * die_2.num_sides
for value in range(1, max_result+1):
frequency = results.count(value)
frequencies.append(frequency)

# Visualize the results.


hist = pygal.Bar()

hist.title = "Results of multiplying two D6 dice. (1,000,000 rolls)"


hist.x_labels = [str(x) for x in range(1, max_result+1)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6 * D6', frequencies)


hist.render_to_file('dice_visual.svg')

U,4)$%?C5*%*,-'45,6%,6-O%'*)*%3%-5*4%2,<E.)C)6*5,6%8,.%4C)% hist.x_labels %E3.3<)4).H%Q,'%<59C4


@364%4,%4.O%.)E-32569%4C)%,4C).%-,,E*%@54C%2,<E.)C)6*5,6*%3*%@)--H

N'4E'4$
4,E

!"#$%&'()*+$'(%,)+-'.+'/*.&#*.&-0'1"'-$/*##$-+2
!"#$%&'()%*'$%()+),'-).%/0%1#-23/%4'()$%3$#+(%-")%5'06'+%-")6)%/0%7'$8+%98+(:

You might also like