RANDOMIZED DATA POINTS IN MATPLOTLIB
Listing 5.13 displays the content of lin_reg_plot.py that illustrates how to plot a graph of random points.
LISTING 5.13: lin_plot_reg.py
import numpy as np import matplotlib.pyplot as plt trX = np.linspace(-1, 1, 101) # Linear space of 101 and [-1,1] #Create the y function based on the x axis trY = 2*trX + np.random.randn(*trX.shape)*0.4+0.2 #create figure and scatter plot of the random points plt.figure() plt.scatter(trX,trY) # Draw one line with the line function plt.plot (trX, .2 + 2 * trX) plt.show()
Listing 5.13 defines the NumPy variable trX that contains 101 equally spaced numbers that are between -1 and 1 (inclusive). The variable trY is defined in two parts: the first part is 2*trX and the second part is a random value that is partially based on the length of the one-dimensional array trX. The variable trY is the sum of these two “parts,” which creates a “fuzzy” line segment.
The next portion of Listing...