plt.annotate函数案例一则

本文介绍了使用Matplotlib库进行数据可视化的方法,重点讲解了plt.legend和plt.annotate函数的应用,通过生成不同正态分布的数据并绘制图表,展示了如何添加图例和注释,使图表更加丰富和易于理解。

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

观察:plt.legend & plt.annotate两个函数的用法;持续更新中

import numpy as np
import matplotlib.pyplot as plt

# generate different normal distributions
x1 = np.random.normal(30, 3, 100)
x2 = np.random.normal(20, 2, 100)
x3 = np.random.normal(10, 3, 100)

# plot them
plt.figure(figsize=(12,8))
plt.plot(x1, label='plot')
plt.plot(x2, label='2nd plot')
plt.plot(x3, label='last plot')

# generate a legend box
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
       ncol=3, mode="expand", borderaxespad=0.)

# annotate an important value
plt.annotate("Important value", (55,20), xycoords='data',
             xytext=(5, 38), 
             arrowprops=dict(arrowstyle='->')) 
plt.show()

 

# 多项式转换 def polynomial_basis_function(x, degree = 2): """ 输入: - x: tensor, 输入的数据,shape=[N,1] - degree: int, 多项式的阶数 example Input: [[2], [3], [4]], degree=2 example Output: [[2^1, 2^2], [3^1, 3^2], [4^1, 4^2]] 注意:本案例中,在degree>=1时不生成全为1的一列数据;degree为0时生成形状与输入相同,全1的Tensor 输出: - x_result: tensor """ if degree==0: return torch.ones(shape = x.shape,dtype=torch.float32) x_tmp = x x_result = x_tmp for i in range(2, degree+1): x_tmp = torch.multiply(x_tmp,x) # 逐元素相乘 x_result = torch.concat((x_result,x_tmp),axis=-1) return x_result plt.rcParams['figure.figsize'] = (12.0, 8.0) for i, degree in enumerate([0, 1, 3, 8]): # []中为多项式的阶数 model = Linear(degree) X_train_transformed = polynomial_basis_function(X_train.reshape([-1,1]), degree) X_underlying_transformed = polynomial_basis_function(X_underlying.reshape([-1,1]), degree) model = optimizer_lsm(model,X_train_transformed,y_train.reshape([-1,1])) #拟合得到参数 y_underlying_pred = model(X_underlying_transformed).squeeze() print(model.params) # 绘制图像 plt.subplot(2, 2, i + 1) plt.scatter(X_train, y_train, facecolor="none", edgecolor='#e4007f', s=50, label="train data") plt.plot(X_underlying, y_underlying, c='#000000', label=r"$\sin(2\pi x)$") plt.plot(X_underlying, y_underlying_pred, c='#f19ec2', label="predicted function") plt.ylim(-2, 1.5) plt.annotate("M={}".format(degree), xy=(0.95, -1.4)) #plt.legend(bbox_to_anchor=(1.05, 0.64), loc=2, borderaxespad=0.) plt.legend(loc='lower left', fontsize='x-large') plt.savefig('ml-vis3.pdf') plt.show()报错TypeError Traceback (most recent call last) Cell In[113], line 5 3 for i, degree in enumerate([0, 1, 3, 8]): # []中为多项式的阶数 4 model = Linear(degree) ----> 5 X_train_transformed = polynomial_basis_function(X_train.reshape([-1,1]), degree) 6 X_underlying_transformed = polynomial_basis_function(X_underlying.reshape([-1,1]), degree) 8 model = optimizer_lsm(model,X_train_transformed,y_train.reshape([-1,1])) #拟合得到参数 Cell In[112], line 15, in polynomial_basis_function(x, degree) 3 """ 4 输入: 5 - x: tensor, 输入的数据,shape=[N,1] (...) 11 - x_result: tensor 12 """ 14 if degree==0: ---> 15 return torch.ones(shape = x.shape,dtype=torch.float32) 17 x_tmp = x 18 x_result = x_tmp TypeError: ones() received an invalid combination of arguments - got (shape=torch.Size, dtype=torch.dtype, ), but expected one of: * (tuple of ints size, *, tuple of names names, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)如何修改
07-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值