Answered step by step
Verified Expert Solution
Question
1 Approved Answer
import matplotlib.pyplot as pltimport numpy as npfrom numpy.polynomial import Polynomialdef plot _ web _ traffic ( x , y , models = None ) :
import matplotlib.pyplot as pltimport numpy as npfrom numpy.polynomial import Polynomialdef plotwebtrafficx y modelsNone: Plot the web traffic y over time x If models is given, it is expected to be a list of fitted models, which will be plotted as well used later in this chapter pltfigurefigsize # width and height of the plot in inches pltscatterx y s plttitleWeb traffic over the last month" pltxlabelTime pltylabelHitshour pltxticksw for w in rangeweek iw for w in range if models: colors pltcmviridisnplinspace lenmodels linestyles : mx nplinspace x for model, color in zipmodels colors: pltplotmx modelmx linestyle linewidth ccolor # Create legend based on model orders pltlegendd i mdegree for m in models loc"upper left" pltautoscaletightTrue pltshowdef calculatetotalerrorx y model: Calculate the total error for a given model. return npsumy modelxdef predicttimetoreachhitsmodel targethits: Predict the time to reach a certain number of hitshour using the model. # Create a range of time values to predict timevalues nplinspace predictedhits modeltimevalues # Find the time where predicted hits reach the target try: timetoreach timevaluespredictedhits targethits except IndexError: timetoreach npnan # If the target is never reached, return NaN return timetoreach# Generate some example datanp.random.seedx nparange # every hour for four weeksy npsinx nppi nprandom.normal lenx# Create polynomial modelsmodels Polynomialfitx y deg for deg in range# Calculate total errors for each modeltotalerrors calculatetotalerrorx y model for model in models# Predict the time to reach hitshour for each modeltargethits predictedtimes predicttimetoreachhitsmodel targethits for model in models# Plot the total error against polynomial degreeplt.figurefigsizepltplotrange totalerrors, markeroplttitleTotal Error vs Polynomial Degree"pltxlabelPolynomial Degree"pltylabelTotal Error"pltgridTruepltshow# Plot the predicted time to reach hitshour against polynomial degreeplt.figurefigsizepltplotrange predictedtimes, markeroplttitlePredicted Time to Reach HitsHour vs Polynomial Degree"pltxlabelPolynomial Degree"pltylabelPredicted Time hourspltgridTruepltshow# Plot the web traffic with the polynomial modelsplotwebtrafficx y modelsmodels
My last graph isn't showing any data. Can you please tell me what im doing wrong?
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started