Matplotlib

Matplotlib Exercises

这里写图片描述

Exercise 11.1: Plotting a function

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    """Compute f(x)"""
    part1 = np.sin(x - 2)
    part2 = np.exp(-np.power(x, 2))
    f = np.power(part1, 2) * part2
    return f

x = np.linspace(0, 2, 1000)
y = [f(i) for i in x]

plt.plot(x, y, 'b-', label = "f(x)")

plt.title("Plotting a function", fontsize = 24)
plt.xlabel("x", fontsize = 24)
plt.ylabel("f(x)", fontsize = 24)
plt.legend()

plt.savefig("Plotting a function.png")
plt.show()

Result of Exercise 11.1

这里写图片描述

Exercise 11.2: Data

import matplotlib.pyplot as plt
import numpy as np
from scipy import linalg

num = 10

X = np.random.randint(-num, num, 200).reshape(20, 10)
b = np.random.randint(-num, num, 10).reshape(10, 1)
z = np.random.normal(loc = 0, scale = 1, size = 20).reshape(20, 1)
y = np.dot(X, b) + z

# Least squares, solve (X.T)Xb = (X.T)y
b_estimate = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)

plt.plot(b, 'ro', b_estimate, 'bx')

plt.title("Data", fontsize = 24)
plt.xlabel("index", fontsize = 24)
plt.ylabel("value", fontsize = 24)
plt.legend(["True param", "Estimated param"])

plt.savefig("Data.png")
plt.show()

Result of Exercise 11.2

这里写图片描述

Exercise 11.3: Histogram and density estimation

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

n = 10000
Ez = 0
Dz = 1

z = np.random.normal(Ez, Dz, n)
z = np.sort(z)

kde = stats.gaussian_kde(z)
plt.plot(z, kde(z), "r-", label = "Gaussian Kernel Density")
plt.hist(z, bins = 25, edgecolor = "black", normed = True, color = "b")
plt.legend()

plt.savefig("Histogram and density estimation.png")
plt.show()

Result of Exercise 11.3

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值