A document from MCS 275 Spring 2023, instructor Emily Dumas. You can also get the notebook file.

MCS 275 Spring 2023 Homework 11 Solutions

  • Course Instructor: Emily Dumas
  • Contributors to this document: Kylash Viswanathan

Instructions:

  • Complete the problems below, which ask you to write matplotlib code in a Python notebook.
  • Upload the resulting notebook directly to gradescope, i.e. upload the .ipynb file containing your work.

Deadline

This homework assignment must be submitted in Gradescope by Noon central time on Tuesday April 4, 2023.

Collaboration

Collaboration is prohibited, and you may only access resources (books, online, etc.) listed below.

Content

This homework is about matplotlib.

Resources you may consult

Most relevant:

Less likely to be relevant, but also allowed:

Point distribution

This homework assignment has 2 problems, numbered 2 and 3. The grading breakdown is:

Points Item
3 Autograder
6 Problem 2
6 Problem 3
15 Total

The part marked "autograder" reflects points assigned to your submission based on some simple automated checks for Python syntax, etc. The result of these checks is shown immediately after you submit.

What to do if you're stuck

Ask your instructor or TA a question by email, in office hours, or on discord.

Submit as a notebook

Submit your work on this assignment as a notebook file hwk11.ipynb. You can create that notebook from scratch or you can just add your solutions to the notebook file containing the assignment. Do whatever you find most convenient.

Problem 2: Plot from description

Make a figure with a single set of axes. The horizontal axis should be labeled $n$ and the vertical axis should be labeled $y$. Two sets of data should be shown on those axes:

  • For integers $n$ from 0 to 20, the points $(n,\log(F_n))$ where $F_n$ is the $n^{\mathrm{th}}$ Fibonacci number, should be marked by blue dots (not joined by lines at all).
  • The line $y = c n$ where $c=\log \left ( \frac{1 + \sqrt{5}}{2} \right ) \approx 0.48121182505960347$ is drawn in red, with a thin line width.

Give the plot a title "Log Fibonacci numbers".

Note: The $n^{\mathrm{th}}$ Fibonacci number is quite close to $\left (\frac{1 + \sqrt{5}}{2} \right)^n$, so your plot should show a line and a bunch of dots that are close to that line!

Solution

In [21]:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
In [22]:
def fibonacci(n):
    """
    A recursive definition of the Fibonacci sequence
    """
    if n < 0:
        raise TypeError("Only non-negative integers are allowed")
        
    elif n <= 1: # Base Case
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2) 

# Sequence generation
input_vals = list(range(0,21)) 
logfib_seq = [np.log(fibonacci(x)) for x in input_vals] 
logfib_approx = [np.log((1 + np.sqrt(5)) / 2) * x for x in input_vals] 

# Plot formatting
fig, ax = plt.subplots() 

#plotting of fib seq and approximation
ax.scatter(input_vals, logfib_seq, color = 'blue') 
ax.plot(input_vals, logfib_approx, color = 'red', linewidth = .5) 

# axis and title labels
ax.set_xlabel('n')
ax.set_ylabel('y')
ax.set_title('Log Fibonacci numbers')

# graph is shown
plt.show()

Problem 3: Plot from picture

Write matplotlib code to produce a plot as similar to this one as you can manage. (Including the grid lines you see here is optional; they're the default in the stylesheet recommended in VanderPlas's book.)

Solution

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
In [20]:
axis_spacing = np.linspace(-4, 5, 10) 
dot_placement = np.linspace(6, 6,10)
dot_size = np.linspace(10, 100, 10)

plt.figure(figsize=(6,6),dpi=120)

#top perimeter
plt.scatter(axis_spacing, dot_placement, color="red", s = dot_size) 

#bottom perimeter
plt.scatter(-axis_spacing, -dot_placement, color="green", s = dot_size) 

#left perimeter
plt.scatter(-dot_placement, axis_spacing, color="blue", s = dot_size) 

#right perimeter
plt.scatter(dot_placement, -axis_spacing, color="yellow", s = dot_size) 

#center placement
plt.scatter(0, 0, color = "purple", s = 8000)


# Axis Labels
plt.xlabel("Interestingness")
plt.ylabel("Electronegativity")

plt.show()

Revision history

  • 2023-03-31 Initial publication