高级编程技术 Matplotlib课后习题

本文介绍了使用Python进行数据生成、绘图及简单的数据分析过程。包括绘制特定函数图像、通过最小二乘法估计系数并对比真实系数,以及生成正态分布样本进行直方图与密度估计的绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

步骤如下:

(1)f, ax = plt.subplots(1, 1, figsize=(5,4))  ------先用subplot画图;

(2)x = np.linspace(0, 2, 200)  ------生成0到2的200个均匀分布数;

(3)y = (np.sin(x - 2) ** 2) * (np.exp(-(x ** 2)))  ------生成函数 

(4)ax.set_xlim((0, 2))   ax.set_ylim((0, 1))   ------设置显示部分的定义域和值域;

(5)ax.set_xlabel("x-axis")   ax.set_ylabel("y-axis")   ax.set_title("Exercise 11.1: Plotting a function")   ------给横坐标,纵坐标和标题附上名字;

(6)plt.savefig("Exercise 11.1.pdf")    ------保存图像。

完整代码如下:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

f, ax = plt.subplots(1, 1, figsize=(5,4))

x = np.linspace(0, 2, 200)
y = (np.sin(x - 2) ** 2) * (np.exp(-(x ** 2)))
ax.plot(x, y)
ax.set_xlim((0, 2))
ax.set_ylim((0, 1))
ax.set_xlabel("x-axis")
ax.set_ylabel("y-axis")
ax.set_title("Exercise 11.1: Plotting a function")

plt.savefig("Exercise 11.1.pdf")

画图如下:





步骤如下:

(1)variables = np.random.randint(-5, 5, 10).tolist()    -------生成范围从-5到5的10个变量。

(2)X = np.random.normal(variables[0], 1, size=(20,1))
         for i in range(1, 10):
      observation = np.random.normal(variables[i], 1, size=(20,1))

      X = np.hstack((X, observation))

        ------- 对于每个变量variablie,用均值等于variablie,方差等于1的正态分布再生成这个变量的20个观测值。

(3)true_b = np.random.uniform(-1.5, 1.5, 10).reshape(10,1)   

        ------ 因为题目没有要求b应该满足什么条件,所以就使用10个范围从-1.5到1.5的均匀分布来生成b。

(4)z = np.random.normal(size = (20,1))

        ------ 使用正态分布生成z

(5)y = np.dot(X, true_b) + z

        ------ 计算 y

(6)estimated_b = np.linalg.lstsq(X, y,None)[0]

        ------ 计算 X 和 y 的最小二乘

(7)plt.scatter(range(10), true_b, c = 'r',marker = 'x')

         plt.scatter(range(10), estimated_b,c = 'b', marker = 'o')

       ------ 画散点图

(8)plt.legend(['True coefficients','Estimated coefficients'])

       ------ 显示图例

(9)plt.xlim(0, 9)           plt.ylim(-1.5, 1.5)

        ------ 设置显示部分的定义域和值域;

(10)plt.hlines(0, 0, 9, colors = 'b', linestyles = 'dashed')

        ------ 在图的正中间画一条蓝色的虚线;

(11)plt.title('Exercise 11.2: Data')

       ------ 设置标题

(12)plt.show()

        ------ 画图,大功告成

完整代码如下:

import matplotlib.pyplot as plt
import numpy as np

variables = np.random.randint(-5, 5, 10).tolist()
X = np.random.normal(variables[0], 1, size=(20,1))
for i in range(1, 10):
	observation = np.random.normal(variables[i], 1, size=(20,1))
	X = np.hstack((X, observation))
	
true_b = np.random.uniform(-1.5, 1.5, 10).reshape(10,1)

z = np.random.normal(size = (20,1))

y = np.dot(X, true_b) + z

estimated_b = np.linalg.lstsq(X, y,None)[0]

plt.scatter(range(10), true_b, c = 'r',marker = 'x')
plt.scatter(range(10), estimated_b,c = 'b', marker = 'o')

plt.legend(['True coefficients','Estimated coefficients'])

plt.xlim(0, 9)
plt.ylim(-1.5, 1.5)

plt.title('Exercise 11.2: Data')

plt.hlines(0, 0, 9, colors = 'b', linestyles = 'dashed')

plt.show()

画图如下:





步骤如下:

(1)distribution = np.random.normal(size=10000)

        ------ 选择分布为正态分布,取10000个样本值。

(2)linspace = np.linspace(4, -4, 100)

        ------ 设置取值空间

(3)value = stats.gaussian_kde(distribution).evaluate(linspace)

        ------ 通过 stats.gaussian_kde 求 distribution 在 linspace 上的概率分布。

(4)plt.hist(distribution, bins=25, normed = 1, color = 'b', edgecolor = 'k')

        ------ 画柱状图,颜色是蓝色,边缘颜色是黑色。

(5)plt.plot(linspace, value, color='r')

        ------ 画正态分布图,颜色是红色

(6)plt.title('Exercise 11.3: Histogram and density estimation')

        ------ 设置标题

(7)plt.show()

         ------ 画图,大功告成

完整代码如下:

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

distribution = np.random.normal(size=10000)

linspace = np.linspace(4, -4, 100)

value = stats.gaussian_kde(distribution).evaluate(linspace)


plt.hist(distribution, bins=25, normed = 1, color = 'b', edgecolor = 'k')

plt.plot(linspace, value, color='r')

plt.title('Exercise 11.3: Histogram and density estimation')

plt.show()

画图如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值