matplotlib画图、标点、打标签

本文详细介绍使用Python的matplotlib和numpy库进行函数图形绘制的方法,包括如何调整坐标轴、标注关键点及其坐标,并通过虚线突出显示。同时,介绍了如何为图形添加标题、保存图片,以及如何将坐标轴调整到原点位置。

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

Rendering

这是想要的效果:
function-point-label

Notes

记录几个功能的做法:

  • 函数作图
  • 座标轴(下、左边框)移到过原点,上、右边框去掉
  • 标出一个点
  • 虚线描出这个点的横、纵坐标所在
  • 给这个点打标签
  • 图片标题
  • 保存

Code

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

# 函数图
x = np.arange(0, 3, 0.01)
y = x ** 2 - 3 * x + 2
plt.plot(x, y)

# 标题
plt.title('x^2 - 3x + 2')

# 标点
plt.scatter([1.5], [-0.25], s=25, c='r')  # stroke, colour

# 虚线定位:两点确定一条直线
plt.plot([0, 1.5], [-0.25, -0.25], c='b', linestyle='--')
plt.plot([1.5, 1.5], [0, -0.25], c='b', linestyle='--')

# 点的标签(座标中加减的 `0.15` 是显示位置的偏移,避免挡住点)
plt.text(1.5+0.15, -0.25-0.15, 'minima', ha='center', va='bottom', fontsize=10.5)  # horizontal alignment
# 座标轴调位
ax = plt.gca()
# 去掉上、右边框
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
# 移到原点
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

# 显示、保存
plt.show()
fig.savefig('fun.png')
# load checkpoints,如何上线 model = Sequence2Sequence(len(src_word2idx), len(trg_word2idx)) model.load_state_dict(torch.load(f"./best.ckpt", weights_only=True,map_location="cpu")) class Translator: def __init__(self, model, src_tokenizer, trg_tokenizer): self.model = model self.model.eval() # 切换到验证模式 self.src_tokenizer = src_tokenizer self.trg_tokenizer = trg_tokenizer def draw_attention_map(self, scores, src_words_list, trg_words_list): """绘制注意力热力图 Args: - scores (numpy.ndarray): shape = [source sequence length, target sequence length] """ plt.matshow(scores.T, cmap='viridis') # 注意力矩阵,显示注意力分数值 # 获取当前的轴 ax = plt.gca() # 设置热图中每个单元格的分数的文本 for i in range(scores.shape[0]): #输入 for j in range(scores.shape[1]): #输出 ax.text(j, i, f'{scores[i, j]:.2f}', # 格式化数字显示 ha='center', va='center', color='k') plt.xticks(range(scores.shape[0]), src_words_list) plt.yticks(range(scores.shape[1]), trg_words_list) plt.show() def __call__(self, sentence): sentence = preprocess_sentence(sentence) # 预处理句子,标点符号处理等 encoder_input, attn_mask = self.src_tokenizer.encode( [sentence.split()], padding_first=True, add_bos=True, add_eos=True, return_mask=True, ) # 对输入进行编码,并返回encode_piadding_mask encoder_input = torch.Tensor(encoder_input).to(dtype=torch.int64) # 转换成tensor preds, scores = model.infer(encoder_input=encoder_input, attn_mask=attn_mask) #预测 trg_sentence = self.trg_tokenizer.decode([preds], split=True, remove_eos=False)[0] #通过tokenizer转换成文字 src_decoded = self.src_tokenizer.decode( encoder_input.tolist(), split=True, remove_bos=False, remove_eos=False )[0] #对输入编码id进行解码,转换成文字,为了画图 self.draw_attention_map( scores.squeeze(0).numpy(), src_decoded, # 注意力图的源句子 trg_sentence # 注意力图的目标句子 ) return " ".join(trg_sentence[:-1])这段代码有什么用
最新发布
03-14
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值