import matplotlib.pyplot as plt
squares = [number ** 2 for number in range(1, 6)]
plt.plot(squares)
plt.show()
<matplotlib.figure.Figure at 0x10eb07ac8>
plt.plot(squares, linewidth=5)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.show()
x_values = range(1, 6)
y_values = squares
plt.plot(x_values, y_values, linewidth=5)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.show()
scatter()
¶plt.scatter(2, 4)
plt.show()
plt.scatter(2, 4, s=100)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
scatter()
¶plt.scatter(x_values, y_values, s=100)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
x_values = range(1, 1001)
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, s=20)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.axis([0, 1100, 0, 1100000])
plt.show()
plt.scatter(x_values, y_values, s=20, c=(0, 0, 0.8), edgecolor='none')
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.axis([0, 1100, 0, 1100000])
plt.show()
plt.scatter(x_values, y_values, s=20, c=y_values, cmap=plt.cm.Blues, edgecolor='none')
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.axis([0, 1100, 0, 1100000])
plt.show()
plt.scatter(x_values, y_values, s=20, c=y_values, cmap=plt.cm.Blues, edgecolor='none')
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.axis([0, 1100, 0, 1100000])
plt.savefig('squares_plot.png', bbox_inches='tight')
# 15-1. Cubes: A number raised to the third power is a cube.
# Plot the first five cubic numbers, and then plot the first 5000
# cubic numbers.
x_values = range(1, 6)
y_values = [x**3 for x in x_values]
plt.scatter(x_values, y_values, s=30)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
x_values = range(1, 5001)
y_values = [x**3 for x in x_values]
plt.scatter(x_values, y_values, s=30)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
# 15-2. Colored cubes: Apply a colormap to your cubes plot.
x_values = range(1, 5001)
y_values = [x**3 for x in x_values]
plt.scatter(x_values, y_values, s=30, c=y_values, cmap=plt.cm.Reds)
plt.title('Square Numbers', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
from random import choice
class RandomWalk():
""""A class to generate random walks."""
def __init__(self, num_points=5000):
self.num_points = num_points
# All walks atart at (0, 0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in the walk."""
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# Reject moves that go nowhere.
if x_step == 0 and y_step == 0:
continue
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)
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=2)
plt.show()
while True:
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=2)
plt.show()
keep_running = input('Make another walk? (y/n): ')
if keep_running.lower() == 'n':
break
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): n
while True:
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=2)
plt.show()
keep_running = input('Make another walk? (y/n): ')
if keep_running.lower() == 'n':
break
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): n
while True:
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=2)
plt.scatter(rw.x_values[0], rw.y_values[0], c='green', edgecolors='none', s=20)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=20)
plt.show()
keep_running = input('Make another walk? (y/n): ')
if keep_running.lower() == 'n':
break
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): n
while True:
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=2)
plt.scatter(rw.x_values[0], rw.y_values[0], c='green', edgecolors='none', s=20)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=20)
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.lower() == 'n':
break
/usr/local/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): n
import matplotlib.pyplot as plt
while True:
rw = RandomWalk(50_000)
rw.fill_walk()
plt.figure(figsize=(12, 8))
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)
plt.scatter(rw.x_values[0], rw.y_values[0], c='green', edgecolors='none', s=20)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=20)
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.lower() == 'n':
break
/usr/local/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): y
Make another walk? (y/n): n
# 15-3. Molecular motion: Replace plt.scatter() with plt.plot().
# To simulate the path of a pollen grain on the servace of a drop of
# water, pass in the `rw.x_values` and `rw.y_values`, and include a
# `linewidth` argument. Use 5000 instead of 50,000 points.
rw = RandomWalk(5_000)
rw.fill_walk()
plt.figure(figsize=(12, 8))
point_numbers = list(range(rw.num_points))
plt.plot(rw.x_values, rw.y_values, linewidth=2)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
/usr/local/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
# 15-4. Modified random walks: In the class `RandomWalk`, `x_step` and `y_step`
# are generated from the same set of conditions. The direction is chosen randomly
# from the list `[1, -1]` and the distance from the list `[0, 1, 2, 3, 4]`.
# Modify the values in these lists to see what happens to the overall shape of
# your walks. Try a longer list of choices for the distance, such as 0 through 8,
# or remove the -1 from the x or y direction list.
from random import choice
class RandomWalk():
""""A class to generate random walks."""
def __init__(self, num_points=5000):
self.num_points = num_points
# All walks atart at (0, 0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in the walk."""
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1])
y_step = y_direction * y_distance
# Reject moves that go nowhere.
if x_step == 0 and y_step == 0:
continue
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)
rw = RandomWalk(5_000)
rw.fill_walk()
plt.figure(figsize=(8, 8))
point_numbers = list(range(rw.num_points))
plt.plot(rw.x_values, rw.y_values, linewidth=2)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
/usr/local/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
# 15-5. Refactoring: The method `fill_walk()` is length. Create a new method
# called `get_step()` to determine the direction and distance for each step,
# and then calculate the step. You should end up with two calls to `get_step()`
# in `fill_walk()`: x_step = get_step()... y_step = get_step()
class RandomWalk():
""""A class to generate random walks."""
def __init__(self, num_points=5000):
self.num_points = num_points
# All walks atart at (0, 0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in the walk."""
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
# Reject moves that go nowhere.
if x_step == 0 and y_step == 0:
continue
self.x_values.append(self.x_values[-1] + x_step)
self.y_values.append(self.y_values[-1] + y_step)
def get_step(self):
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4, 5])
return direction * distance
rw = RandomWalk(5_000)
rw.fill_walk()
plt.figure(figsize=(8, 8))
point_numbers = list(range(rw.num_points))
plt.plot(rw.x_values, rw.y_values, linewidth=2)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
/usr/local/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
> pip3 install pygal
Visit http://www.pygal.org
Die
class¶from random import randint
class Die():
"""A class representing a single die."""
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
"""Return a random value between 1 and the number of sides."""
return randint(1, self.num_sides)
die = Die()
results = [die.roll() for roll_num in range(100)]
print(results)
[5, 4, 3, 5, 5, 6, 5, 3, 2, 6, 2, 6, 3, 5, 5, 2, 3, 1, 4, 3, 6, 6, 4, 1, 1, 5, 5, 2, 1, 6, 3, 5, 3, 1, 1, 3, 2, 3, 4, 6, 5, 5, 3, 3, 4, 3, 1, 3, 2, 2, 2, 6, 1, 3, 6, 5, 1, 6, 4, 1, 4, 3, 1, 6, 1, 4, 4, 1, 2, 3, 2, 2, 4, 1, 3, 6, 5, 3, 1, 2, 1, 3, 1, 6, 3, 2, 3, 3, 3, 3, 1, 1, 4, 2, 1, 6, 1, 3, 5, 3]
results = [die.roll() for roll_num in range(1_000)]
frequencies = [results.count(value) for value in range(1, die.num_sides + 1)]
print(frequencies)
[174, 171, 166, 165, 154, 170]
import pygal
hist = pygal.Bar()
hist.title = 'Results of rolling one D6 1000 times.'
hist.x_labels = [str(num) for num 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('chapter_15_output/die_visual.svg')
die_1 = Die()
die_2 = Die()
results = [die_1.roll() + die_2.roll() for roll_num in range(1_000)]
frequencies = [results.count(value) for value in range(2, die_1.num_sides + die_2.num_sides + 1)]
hist = pygal.Bar()
hist.title = 'Results of rolling two D6 dice 1000 times.'
hist.x_labels = [str(num) for num in range(2, die_1.num_sides + die_2.num_sides + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D6 + D6', frequencies)
hist.render_to_file('chapter_15_output/dice_visual.svg')
die_1 = Die()
die_2 = Die(10)
results = [die_1.roll() + die_2.roll() for roll_num in range(50_000)]
frequencies = [results.count(value) for value in range(2, die_1.num_sides + die_2.num_sides + 1)]
hist = pygal.Bar()
hist.title = 'Results of rolling a D6 and D10 50,000 times.'
hist.x_labels = [str(num) for num in range(2, die_1.num_sides + die_2.num_sides + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D6 + D10', frequencies)
hist.render_to_file('chapter_15_output/diff_size_dice_visual.svg')
# 15-6. Automatic labels: Replace the list we used to set the value of `hist.x_labels`
# with a loop to generate this list automatically. If you're comfortable with list
# comprehensions, try replacing the other `for` loops with comprehensions as well.
# DONE!
# 15-7. Two D8s: Create a simulation showing what happens if you roll two eight-sided
# dice 1,000 times. Increase the number of rolls gradually until you start to see the
# limits of your system's capabilities.
die_1 = Die(8)
die_2 = Die(8)
results = [die_1.roll() + die_2.roll() for roll_num in range(1_000_000)]
frequencies = [results.count(value) for value in range(2, die_1.num_sides + die_2.num_sides + 1)]
hist = pygal.Bar()
hist.title = 'Results of rolling two D8 dice 1,000,000 times.'
hist.x_labels = [str(num) for num in range(2, die_1.num_sides + die_2.num_sides + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D8 + D8', frequencies)
hist.render_to_file('chapter_15_output/8_sided_dice_visual.svg')
# 15-8. Three dice: If you roll three D6 dice, the smallest number you can roll
# is 3 and the largest number is 18. Create a visualization that shows what happens
# when you roll three D6 dice.
die_1 = Die()
die_2 = Die()
die_3 = Die()
results = [die_1.roll() + die_2.roll() + die_3.roll() for roll_num in range(100_000)]
frequencies = [results.count(value) for value in range(3, die_1.num_sides + die_2.num_sides + die_3.num_sides + 1)]
hist = pygal.Bar()
hist.title = 'Results of rolling three D6 dice 100,000 times.'
hist.x_labels = [str(num) for num in range(3, die_1.num_sides + die_2.num_sides + die_3.num_sides + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D6 + D6 + D6', frequencies)
hist.render_to_file('chapter_15_output/3_D6_visual.svg')
# 15-9. Multiplication: When you roll two dice, you usually add the two numbers
# together to get the result. Create a visualization that shows what happens if
# you multiply these numbers instead.
die_1 = Die()
die_2 = Die()
results = [die_1.roll() * die_2.roll() for roll_num in range(10_000)]
frequencies = [results.count(value) for value in range(1, die_1.num_sides * die_2.num_sides + 1)]
hist = pygal.Bar()
hist.title = 'Results of rolling two D6 dice 10,000 times.'
hist.x_labels = [str(num) for num in range(1, die_1.num_sides * die_2.num_sides + 1)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D6 + D6', frequencies)
hist.render_to_file('chapter_15_output/dice_multiply_visual.svg')