如何调整图例(legend)内标记(marker)位置 避免遮挡线型样式
方法1:快速调整(无需自定义类)
先生成图例后直接修改标记的坐标位置,适合快速调参适配:
import matplotlib.pyplot as plt # 你的绘图逻辑示例 fig, ax = plt.subplots() l1, = ax.plot([1,2,3], [1,2,3], linestyle='--', c='#1f77b4', marker='s', markersize=7, label='序列1') l2, = ax.plot([1,2,3], [2,3,4], linestyle='-.', c='#ff7f0e', marker='o', markersize=7, label='序列2') # 生成图例,先把线段长度调长避免太挤 leg = ax.legend(handlelength=3) # 遍历图例中的标记,修改偏移量:正数向右偏移,负数向左偏移 for marker in leg.get_lines()[1::2]: x = marker.get_xdata() marker.set_xdata(x + 8) # 偏移量可根据实际显示效果调整 plt.show()
方法2:自定义图例处理器(稳定复用)
如果需要多个图统一效果,可自定义Line2D的图例处理器,一次定义多次使用:
import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerLine2D # 自定义偏移标记的处理器 class ShiftMarkerHandler(HandlerLine2D): def create_artists(self, legend, orig_handle, xd, yd, width, height, fs, trans): artists = super().create_artists(legend, orig_handle, xd, yd, width, height, fs, trans) line, marker = artists # 调整标记的x轴位置,0.7代表放在线段70%的位置,0就是最左,1就是最右 marker.set_xdata([width * 0.7]) return artists # 绘图逻辑 fig, ax = plt.subplots() l1, = ax.plot([1,2,3], [1,2,3], linestyle='--', marker='s', markersize=7, label='序列1') l2, = ax.plot([1,2,3], [2,3,4], linestyle='-.', marker='o', markersize=7, label='序列2') # 生成图例时指定处理器 ax.legend( handler_map={plt.Line2D: ShiftMarkerHandler(numpoints=1)}, handlelength=3 # 可调整线段总长度 ) plt.show()
两种方法都可以自由调整标记的左右位置,完整露出线型样式,不需要手动后期编辑图片。
内容的提问来源于stack exchange,提问作者serycjon
相关产品推荐
相关产品推荐

