如何在Matplotlib中绘制带箭头坐标轴并实现指定可视化需求
实现Matplotlib可视化的三个定制需求
需求列表
- 为x轴和y轴添加箭头
- 仅显示数据中实际用到的数值作为刻度
- 为每个散点坐标添加标签
当前代码
x = [9, 8, 11, 11, 14, 13, 16, 14, 14] y = [9, 16, 15, 11, 10, 11, 10, 8, 8] fig = plt.figure(figsize=(7,7), dpi=300) axes = fig.add_axes([0,1,1,1]) axes.set_xlim(0, 17) axes.set_ylim(0, 17) axes.invert_yaxis() axes.scatter(x, y, color='green') axes.vlines(x, 0, y, linestyle="dashed", color='green') axes.hlines(y, 0, x, linestyle="dashed", color='green') axes.spines.right.set_visible(False) axes.spines.bottom.set_visible(False) plt.show()
效果对比
当前可视化效果:
目标可视化效果:
修改后的代码及实现说明
import matplotlib.pyplot as plt x = [9, 8, 11, 11, 14, 13, 16, 14, 14] y = [9, 16, 15, 11, 10, 11, 10, 8, 8] fig = plt.figure(figsize=(7,7), dpi=300) axes = fig.add_axes([0,1,1,1]) # 1. 调整轴位置并添加箭头 # 将y轴移至x=0位置,x轴移至y=0位置 axes.spines['left'].set_position(('data', 0)) axes.spines['bottom'].set_position(('data', 0)) # 隐藏不需要的轴 axes.spines.right.set_visible(False) axes.spines.top.set_visible(False) # 为轴添加箭头样式 axes.spines['left'].set_arrowstyle('->') axes.spines['bottom'].set_arrowstyle('->') # 2. 设置仅显示实际用到的数值作为刻度 # 提取x、y中的唯一值并排序 unique_x = sorted(list(set(x))) unique_y = sorted(list(set(y))) axes.set_xticks(unique_x) axes.set_yticks(unique_y) # 保持y轴反转 axes.invert_yaxis() # 绘制散点、垂直线和水平线 axes.scatter(x, y, color='green') axes.vlines(x, 0, y, linestyle="dashed", color='green') axes.hlines(y, 0, x, linestyle="dashed", color='green') # 3. 为每个坐标点添加标签 for xi, yi in zip(x, y): # 标签位置稍微偏移,避免覆盖散点 axes.text(xi + 0.2, yi + 0.2, f'({xi}, {yi})', fontsize=8) plt.show()
关键实现细节
- 轴箭头:通过
spines.set_position将轴移至坐标原点,再用set_arrowstyle添加箭头样式,同时隐藏右侧和顶部的轴。 - 自定义刻度:提取数据中的唯一值并排序,直接设置为轴的刻度,确保只显示实际用到的数值。
- 坐标点标签:遍历所有坐标对,用
text方法在每个点的右上角添加坐标标签,通过偏移量避免遮挡散点。
内容的提问来源于stack exchange,提问作者Valerie
相关产品推荐
相关产品推荐

