我是靠谱客的博主 欢喜海燕,这篇文章主要介绍《Python数据分析基础教程:Numpy学习指南》- 速记 - 第九章,现在分享给大家,希望可以做个参考。

9.2 绘制多项式函数

复制代码
1
2
3
4
5
6
7
8
9
import numpy as np import matplotlib.pyplot as plt func = np.poly1d(np.array([1, 2, 3, 4]).astype(float)) x = np.linspace(-10, 10, 30) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y(x)') plt.show()

9.4 绘制多项式函数及其导函数

复制代码
1
2
3
4
5
6
7
8
9
10
11
import numpy as np import matplotlib.pyplot as plt func = np.poly1d(np.array([1, 2, 3, 4]).astype(float)) func1 = func.deriv(m=1) x = np.linspace(-10, 10, 30) y = func(x) y1 = func1(x) plt.plot(x, y, 'ro', x, y1, 'g--') plt.xlabel('x') plt.ylabel('y') plt.show()

9.6 绘制多项式函数及其导函数

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np import matplotlib.pyplot as plt func = np.poly1d(np.array([1, 2, 3, 4]).astype(float)) x = np.linspace(-10, 10, 30) y = func(x) func1 = func.deriv(m=1) #一次导数 y1 = func1(x) func2 = func.deriv(m=2) #二次导数 y2 = func2(x) plt.subplot(311) plt.plot(x, y, 'r-' ) plt.title("Polynomial") plt.subplot(312) plt.plot(x, y1, 'b^') plt.title("First Derivative") plt.subplot(313) plt.plot(x, y2, 'go') plt.title("Second Derivative") plt.xlabel('x') plt.ylabel('y') plt.show()

9.8 绘制全年股票价格

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator from matplotlib.finance import quotes_historical_yahoo from matplotlib.finance import candlestick import sys from datetime import date import matplotlib.pyplot as plt today = date.today() start = (today.year - 1, today.month, today.day) #将当前的日期减去1年作为起始日期 #创建定位器(locator),这些来自matplotlib.dates包中的对象可以在x轴上定位月份和日期。 alldays = DayLocator() months = MonthLocator() #创建一个日期格式化器(date formatter)以格式化x轴上的日期。该格式化器将创建一个字符串,包含简写的月份和年份。 month_formatter = DateFormatter("%b %Y") #股票名称 symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] #从雅虎财经频道下载股价数据。 quotes = quotes_historical_yahoo(symbol, start, today) fig = plt.figure() ax = fig.add_subplot(111) #将x轴上的主定位器设置为月定位器。该定位器负责x轴上较粗的刻度。 ax.xaxis.set_major_locator(months) #将x轴上的次定位器设置为日定位器。该定位器负责x轴上较细的刻度。 ax.xaxis.set_minor_locator(alldays) #将x轴上的主格式化器设置为月格式化器。该格式化器负责x轴上较粗刻度的标签。 ax.xaxis.set_major_formatter(month_formatter) #可以指定K线图的矩形宽度,现在先使用默认值。 candlestick(ax, quotes) #将x轴上的标签格式化为日期。为了更好地适应x轴的长度,标签将被旋转。 fig.autofmt_xdate() plt.show()

9.10 绘制股价分布直方图

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from matplotlib.finance import quotes_historical_yahoo import sys from datetime import date import matplotlib.pyplot as plt import numpy as np today = date.today() start = (today.year - 1, today.month, today.day) symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] quotes = quotes_historical_yahoo(symbol, start, today) quotes = np.array(quotes) close = quotes.T[4] #提取出收盘价数据 plt.hist(close, np.sqrt(len(close))) plt.show()

9.12 绘制股票成交量

当数据的变化范围很大时,对数坐标图(logarithmic plot)很有用。Matplotlib中有semilogx函数(对x轴取对数)、semilogy函数(对y轴取对数)和loglog函数(同时对x轴和y轴取对数)。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator import sys from datetime import date import matplotlib.pyplot as plt import numpy as np today = date.today() start = (today.year - 1, today.month, today.day) symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] quotes = quotes_historical_yahoo(symbol, start, today) quotes = np.array(quotes) dates = quotes.T[0] volume = quotes.T[5] alldays = DayLocator() months = MonthLocator() month_formatter = DateFormatter("%b %Y") fig = plt.figure() ax = fig.add_subplot(111) plt.semilogy(dates, volume) ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) fig.autofmt_xdate() plt.show()

9.14 绘制股票收益率和成交量变化的散点图

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from matplotlib.finance import quotes_historical_yahoo import sys from datetime import date import matplotlib.pyplot as plt import numpy as np today = date.today() start = (today.year - 1, today.month, today.day) symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] quotes = quotes_historical_yahoo(symbol, start, today) quotes = np.array(quotes) close = quotes.T[4] volume = quotes.T[5] #计算股票收益率和成交量的变化值 ret = np.diff(close)/close[:-1] #out[n] = a[n+1] - a[n] volchange = np.diff(volume)/volume[:-1] fig = plt.figure() ax = fig.add_subplot(111) #数据点的颜色与股票收益率相关联,数据点的大小与成交量的变化相关联 c,color s,size ax.scatter(ret, volchange, c=ret * 100, s=volchange * 100, alpha=0.5) ax.set_title('Close and volume returns') ax.grid(True) plt.show()

9.16 根据条件进行着色

fill_between函数使用指定的颜色填充图像中的区域。我们也可以选择alpha通道的取值。该函数的where参数可以指定着色的条件。

对股价图进行了着色,低于平均值的收盘价使用了一种颜色,高于平均值的收盘价使用了另外一种不同的颜色。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator import sys from datetime import date import matplotlib.pyplot as plt import numpy as np today = date.today() start = (today.year - 1, today.month, today.day) symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] quotes = quotes_historical_yahoo(symbol, start, today) quotes = np.array(quotes) dates = quotes.T[0] close = quotes.T[4] alldays = DayLocator() months = MonthLocator() month_formatter = DateFormatter("%b %Y") fig = plt.figure() ax = fig.add_subplot(111) ax.plot(dates, close) #对收盘价下方的区域进行着色,依据低于或高于平均收盘价使用不同的颜色填充。 plt.fill_between(dates, close.min(), close, where=close>close.mean(), facecolor="green",alpha=0.4) plt.fill_between(dates, close.min(), close, where=close<close.mean(),facecolor="red", alpha=0.4) ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) ax.grid(True) fig.autofmt_xdate() plt.show()

9.18 使用图例和注释

以用legend函数创建透明的图例,并由Matplotlib自动确定其摆放位置。可以用annotate函数在图像上精确地添加注释,并有很多可选的注释和箭头风格。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator import sys from datetime import date import matplotlib.pyplot as plt import numpy as np today = date.today() start = (today.year - 1, today.month, today.day) symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] quotes = quotes_historical_yahoo(symbol, start, today) quotes = np.array(quotes) dates = quotes.T[0] close = quotes.T[4] fig = plt.figure() ax = fig.add_subplot(111) #计算并绘制指数移动平均线(第3章),分别使用9、12和15作为周期数计算和绘制指数移动平均线。添加了一个图例,并使用注释将其中两条曲线的交点标注了出来。 其中两条曲线的交点标注了出来 其中两条曲线的交点标注了出来。示 方法。分别使用91215作为周期数计算和绘制指数移动平均线。 emas = [] for i in range(9, 18, 3): weights = np.exp(np.linspace(-1., 0., i)) weights / = weights.sum() ema = np.convolve(weights, close)[i-1:-i+1] idx = (i - 6)/3 ax.plot(dates[i-1:], ema, lw=idx, label="EMA(%s)" % (i)) data = np.column_stack((dates[i-1:], ema)) emas.append(np.rec.fromrecords(data, names=["dates", "ema"])) #找到两条指数移动平均曲线的交点。 first = emas[0]["ema"].flatten() second = emas[1]["ema"].flatten() bools = np.abs(first[-len(second):] - second)/second < 0.0001 xpoints = np.compress(bools, emas[1]) #将找到的交点用注释和箭头标注出来,并确保注释文本在交点的不远处。 for xpoint in xpoints: ax.annotate('x', xy=xpoint, textcoords='offset points',xytext=(-50, 30),arrowprops=dict(arrowstyle="->")) #添加一个图例并由Matplotlib自动确定其摆放位置。 leg = ax.legend(loc='best', fancybox=True) #设置alpha通道值,将图例透明化。 leg.get_frame().set_alpha(0.5) alldays = DayLocator() months = MonthLocator() month_formatter = DateFormatter("%b %Y") ax.plot(dates, close, lw=1.0, label="Close") ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) ax.grid(True) fig.autofmt_xdate() plt.show()

9.20 在三维空间中绘图

绘制 z = x**2 + y**2

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from matplotlib import cm fig = plt.figure() #使用3d关键字来指定图像的三维投影。 ax = fig.add_subplot(111, projection='3d') #使用meshgrid函数创建一个二维的坐标网格。 u = np.linspace(-1, 1, 100) x, y = np.meshgrid(u, u) z = x ** 2 + y ** 2 # ax.plot_surface(x, y, z, rstride=4, cstride=4, cmap=cm.YlGnBu_r) #cmap colormap plt.show()

9.22 绘制色彩填充的等高线图

Matplotlib中的等高线3D绘图有两种风格——填充的(contourf)和非填充的(contour)。

复制代码
1
2
3
4
5
6
7
8
9
10
import matplotlib.pyplot as plt import numpy as np from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111) u = np.linspace(-1, 1, 100) x, y = np.meshgrid(u, u) z = x ** 2 + y ** 2 ax.contourf(x, y, z) plt.show()

9.24 制作动画

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure() ax = fig.add_subplot(111) N = 10 x = np.random.rand(N) y = np.random.rand(N) z = np.random.rand(N) #用不同颜色的圆形、小圆点和三角形来绘制三个数据集中的数据点。 circles, triangles, dots = ax.plot(x, 'ro', y, 'g^', z, 'b.') ax.set_ylim(0, 1) plt.axis('off') #定期调用以更新屏幕上的内容。将随机更新两个数据集中的y坐标值。 def update(data): circles.set_ydata(data[0]) triangles.set_ydata(data[1]) return circles, triangles #使用NumPy生成随机数。 def generated: while True: yield np.random.rand(2, N) anim = animation.FuncAnimation(fig, update, generate, interval=150) plt.show()

最后

以上就是欢喜海燕最近收集整理的关于《Python数据分析基础教程:Numpy学习指南》- 速记 - 第九章的全部内容,更多相关《Python数据分析基础教程:Numpy学习指南》-内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(75)

评论列表共有 0 条评论

立即
投稿
返回
顶部