Matplotlib双Y轴图绘制空心圆形失败求助:矩形替代圆形
解决Matplotlib双Y轴图中plt.Circle显示为矩形的问题
嘿,我帮你找到问题所在啦!你画出来的“蓝色矩形”其实是被坐标轴比例严重拉伸后的圆形😅
问题原因
你的x轴范围是250到500(跨度250),而y轴范围是0到0.4(跨度0.4),两者的比例差了好几百倍。plt.Circle默认使用数据坐标,x方向的1单位和y方向的1单位在图上的实际长度完全不一样,所以圆形直接被拉成了扁扁的矩形。
两种解决方案
方案一:用scatter画空心圆(推荐)
这个方法更简单,scatter会自动适配坐标轴的比例,确保标记显示为正圆形。把你原来的Circle相关代码替换成下面这行:
ax1.scatter(300, 0.3, s=1200, edgecolor='g', facecolor='none', zorder=10)
s:控制标记的大小,你可以根据需要调整数值facecolor='none':设置为空心样式zorder=10:确保圆形显示在其他元素上方,不会被线条挡住
方案二:给plt.Circle设置轴坐标变换
如果一定要用plt.Circle,可以让它使用轴坐标(相对于坐标轴的比例,而非数据值),这样圆的形状不会被数据范围影响:
# (0.2, 0.75)表示在坐标轴的20%宽度、75%高度位置 circ = plt.Circle((0.2, 0.75), radius=0.05, edgecolor='g', transform=ax1.transAxes) ax1.add_artist(circ)
这种方式的好处是圆的位置和大小会随窗口缩放保持比例,但需要自己换算轴坐标的位置。
修正后的完整代码(方案一版本)
from matplotlib.patches import * import matplotlib.pyplot as plt # 假设x1, oscillator, x2, absorbance是已定义的数据集 fig = plt.figure() ax1 = plt.gca() markers, stems, base = ax1.stem(x1, oscillator, linefmt='k-', markerfmt='ko') for stem in stems: stem.set_linewidth(1) ax1.set_ylim(0, 0.4) ax1.set_xlim(250, 500) ax1.set_xlabel('Wavelength (nm)') ax1.set_ylabel('Oscillator strength') ax1.annotate('Oscillator strength', xy=(307,0.31), xytext=(325,0.35), arrowprops=dict(arrowstyle= '->', connectionstyle='arc3,rad=0.5', lw=1, color='k')) # 用scatter绘制空心圆形标记 ax1.scatter(300, 0.3, s=1200, edgecolor='g', facecolor='none', zorder=10) ax2 = ax1.twinx() ax2.plot(x2, absorbance, 'r-', linewidth=1) ax2.spines['right'].set_color('red') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylabel('Absorbance', color='r') ax2.annotate('', xy=(414,0.31), xytext=(450,0.33), arrowprops=dict(arrowstyle= '->', connectionstyle='arc3,rad=0.5', lw=1, color='r')) ax2.text(450, 0.33, 'Absorbance', color='red') plt.show()
内容的提问来源于stack exchange,提问作者hu jianxu
相关产品推荐
相关产品推荐

