# -*- coding: utf-8 -*- """ Created on Fri Sep 25 14:09:12 2020 @author: jbobowsk """ # This tutorial demonstrates how to successively add curves and/or data to # a single plot. # I will first import the module numpy and 'matplotlib' which we will use # for ploting. Matplotlib provides a MATLAB-like interface. Many of the # options used for plotting in MATLAB are the same in Matplotlib. import math import numpy as np import matplotlib.pyplot as plt # In basic_plots.py, we said that it was easy to put multiple curves on a # single plot by specifying multiple functions in a single plot command. #First, we use arange to create an array of numbers from 0 to 2*pi in # steps of 0.1. We convert to an array so that we can later use xx in calculations. xx = np.array(np.arange(0, 2*math.pi, 0.1)) print(xx) # Here's a plot with two curves (cos and sin). plt.plot(xx, np.sin(xx), 'k-', xx, np.cos(xx), 'r:', linewidth = 2) plt.xlabel('x') plt.ylabel('y') plt.axis((0, 2*math.pi, -1, 1)) # What if we now wanted to add a third curve to our plot? We just write another # plt.plot statement and it will be added to the graph that we already started. plt.plot(xx, np.sin(xx)**2, 'b--', linewidth = 2) # We can continue to add to our existing plot. Let's also add a legend to # the plot. plt.plot(xx, np.cos(xx)**2, 'g-.', linewidth = 2) plt.legend((r'$\sin x$', r'$\cos x$', r'$\sin^2 x$', r'$\cos^2 x$'),\ loc = 'lower left', frameon=False) # If we were now to write another plot command it would add to the existing plot # To avoid doing that, we should use 'pltfigure()' to start a new window before # making the next plot. plt.figure() # Using a for loop and 'hold on', we can easily add many curve to a single # plot. In the loop below, normrnd(mu, sigma) is used to generate random # numbers drawn from a normal distribution with mean mu and standard # deviation sigma. The normally-distributed random number is obtained using # 'np.random.normal(mu, sigma)' and 'for i in range(10)' loops i from 0 to 9. xx = np.array(np.arange(0, 100, 1)) plt.plot(xx, xx**2, 'k-') plt.xlabel('x') plt.ylabel('y') plotformat = ['k--', 'k:', 'k-.', 'r-', 'r--', 'r:', 'r-.', 'b-', 'b--', 'b:']; mu = 2 sigma = 0.05 for i in range(10): n = np.random.normal(mu, sigma) plt.plot(xx, xx**n, plotformat[i])