Understanding matplotlib xticks syntax

前端 未结 2 1541
[愿得一人]
[愿得一人] 2021-02-05 11:01

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         


        
2条回答
  •  温柔的废话
    2021-02-05 11:59

    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.wihtout plt.autoscale(tight=True) and plt.grid()

    hope it helps.

提交回复
热议问题