如何提升Matplotlib twinx坐标轴的辨识度?
Matplotlib双坐标轴(twinx)的黑白友好标识方法
在使用Matplotlib的twinx()创建双坐标轴时,黑白显示场景下常常难以区分曲线对应的坐标轴,你提到的带圆圈+箭头的标识确实是个巧妙的解决方案,下面直接给你实现方法:
实现思路
通过Matplotlib的annotate()绘制指向坐标轴的箭头,再用text()添加圆圈符号,让标识和对应坐标轴/曲线颜色一致,黑白场景下也能清晰对应。
示例代码
import matplotlib.pyplot as plt import numpy as np # 生成示例数据 x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.exp(x/10) # 创建绘图对象 fig, ax1 = plt.subplots() # 绘制主坐标轴曲线 color = 'tab:blue' ax1.set_xlabel('X轴') ax1.set_ylabel('正弦值', color=color) ax1.plot(x, y1, color=color) ax1.tick_params(axis='y', labelcolor=color) # 创建次坐标轴并绘制曲线 ax2 = ax1.twinx() color = 'tab:red' ax2.set_ylabel('指数值', color=color) ax2.plot(x, y2, color=color) ax2.tick_params(axis='y', labelcolor=color) # 添加主坐标轴的圆圈箭头标识 ax1.annotate('', xy=(1.02, 0.5), xycoords='axes fraction', xytext=(1.05, 0.5), textcoords='axes fraction', arrowprops=dict(arrowstyle='->', color=color)) ax1.text(1.06, 0.5, '○', transform=ax1.transAxes, fontsize=12, color=color) # 添加次坐标轴的圆圈箭头标识 ax2.annotate('', xy=(-0.02, 0.5), xycoords='axes fraction', xytext=(-0.05, 0.5), textcoords='axes fraction', arrowprops=dict(arrowstyle='->', color=color)) ax2.text(-0.06, 0.5, '○', transform=ax2.transAxes, fontsize=12, color=color) plt.tight_layout() plt.show()
关键说明
annotate()的xy参数控制箭头指向坐标轴的位置,xytext控制箭头起点,用axes fraction以坐标轴比例定位,适配不同图大小- 圆圈符号用
text()添加,transform=ax.transAxes确保位置相对坐标轴固定 - 标识颜色和对应坐标轴、曲线一致,黑白打印时也能通过位置+符号清晰区分对应关系
内容的提问来源于stack exchange,提问作者Malo
相关产品推荐
相关产品推荐

