I am reading a book and I came across this code:
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.title(\"Web traffic over the last month\")
plt.xlabel(\"Tim
range is a function in python2
which makes a list for the argument given to it:
range(5) -> [0,1,2,3,4]
range(1,5) -> [1, 2, 3, 4]
in general range(lower_index, upper_index+1)
will generate a list equivalent to
[ lower_index, upper_index]
in python2
,
you can use xrange
for better performance ( as it's uses lazy evaluation, calculating when it is needed) or range
in python3
will do the work as xrange
in python2
.
now for the line:
plt.xticks([w*24*7 for w in range(10)],['week %i'%w for w in range(10)])
actually xticks
is the interval for your x axis ticks or measurement, so as your level of measurement is in hours
so it is better to tick for each hour in a week (i.e. 7 days * 24 hours
) for the week's in the data set,
and the second list comprehension put's the label's
for that one week interval( week 0, week 1 .....)
,
one point to notice is that actually the data set you have used from the book have 748 rows so approximately (748/(24*7)) = 4.45 weeks ,,
so you really can plot the graph using range(5),
the reason the output plot is scaled to week0 - week4 is because of the line
plt.autoscale(tight=True)
,
well without plt.autoscale
the plot would have shown something like this.
hope it helps.
In order to understand range, open python and write in sequence the following commands:
range(7)
range(4,8)
range(3,11,2)
For the list comprehensions within the plt.xticks, they are basically a compact way of writing loops. They are very common, useful and neat. In order to understand them:
[w*2 for w in range(10)]
[w*2 for w in range(10) if w < 4]
Finally, for the command plt.xticks itself you can check http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks for a very brief explanation with simple examples.