use*_*388 15 python matplotlib scipy
我正在读一本书,我遇到了这段代码:
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.title("Web traffic over the last month")
plt.xlabel("Time")
plt.ylabel("Hits/hour")
plt.xticks([w*7*24 for w in range(10)],
['week %i'%w for w in range(10)])
plt.autoscale(tight=True)
plt.grid()
plt.show()
Run Code Online (Sandbox Code Playgroud)
对于上下文,x是一个对应于一小时的整数数组. y是在特定时间内的"点击"(从用户到网站)的数组.
我知道代码累积了所有时间,以便它可以在一周内显示它们,但有人可以解释这些功能的作用吗?我的目标是了解这一行的所有语法:
plt.xticks([w*7*24 for w in range(10)],
['week %i'%w for w in range(10)])
Run Code Online (Sandbox Code Playgroud)
特别:
range?这是生成的:

以下是其他上下文的示例数据:
1 2272
2 nan
3 1386
4 1365
5 1488
6 1337
7 1883
8 2283
9 1335
10 1025
11 1139
12 1477
13 1203
14 1311
15 1299
16 1494
17 1159
18 1365
19 1272
20 1246
21 1071
22 1876
23 nan
24 1410
25 925
26 1533
27 2104
28 2113
29 1993
30 1045
Run Code Online (Sandbox Code Playgroud)
laz*_*rus 11
range是一个函数,在python2其中为给定的参数创建一个列表:
range(5) -> [0,1,2,3,4]
range(1,5) -> [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
通常range(lower_index, upper_index+1)会生成一个等于[ lower_index, upper_index]in 的列表
python2,
你可以使用xrange更好的性能(因为它是采用惰性计算,在需要时计算),或range在python3做这项工作作为xrange中python2.
现在换行:
plt.xticks([w*24*7 for w in range(10)],['week %i'%w for w in range(10)])
Run Code Online (Sandbox Code Playgroud)
实际上xticks是你的x轴刻度或测量的间隔,所以你的测量水平是hours这样的,所以最好勾选一周内每小时(即7 days * 24 hours)数据集中的一周,并且第二个列表理解就是label's对于那一周的间隔( week 0, week 1 .....),
需要注意的一点是,实际上你从书中使用的数据集有748行所以大约(748 /(24*7))= 4.45周,
所以你真的可以使用范围(5)绘制图形,输出图标缩放到第0周 - 第4周的原因是由于线条
plt.autoscale(tight=True),没有plt.autoscale情节会显示这样的东西.
希望能帮助到你.
为了理解范围,打开python并按顺序写入以下命令:
range(7)
range(4,8)
range(3,11,2)
Run Code Online (Sandbox Code Playgroud)
对于plt.xticks中的列表推导,它们基本上是一种编写循环的紧凑方式.它们非常常见,有用且整洁.为了理解它们:
[w*2 for w in range(10)]
[w*2 for w in range(10) if w < 4]
Run Code Online (Sandbox Code Playgroud)
最后,对于命令plt.xticks本身,您可以通过简单的示例查看http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks以获得非常简短的解释.