Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

ANGELA G: I had some advertising data and I

fitted a model to predict sales based on TV ad spending.


I wanted to plot the spending and the sales prediction line of my model
to visually inspect the results.
Using the Matplotlib library, I plotted the data and the resulting
sales prediction line.
I ended up with this prediction line that looked like a spaghetti mess.
To solve this problem, I noticed that when I looked at the TV spending,
I had a long series of points that are not in numerical order.
Matplotlib's plot function creates a line going from one value to the next.
But because the points were not in order,
the line jumps back and forth across the plot creating a mess.
I noticed the same thing happening when plotting other prediction
lines in other data sets, even when I was using different types of models.
What I needed was a series of values that were in order.
I created a copy of my data and sorted the data by the TV budget values.
And then, used this to calculate my sales predictions.
This worked and plotted a smooth continuous prediction line.
However, I wondered if there was a better
way I could get a sorted sequence of points
without creating a copy of my data set.
I decided to use the NumPy function called
linspace, short for linear spacing.
Linspace creates an array of ordered and evenly spaced values.
I then had my model predict sales on this new array of TV budget values.
When I used this to plot my prediction line, it came out nice and clear.
Using linspace for plotting has the additional benefit
of allowing me to see predictions where there may be gaps in my data.
Also, I can use this to extrapolate beyond the range of my data.
I could also use NumPy's arrange function
if I wanted to specify an exact interval between one value to the next.
Linspace and arrange are both helpful functions
to create an array of evenly spaced numbers.
Using this, now my prediction lines come out clear in my plot.

You might also like