本文介绍了使用非线性刻度将 twinx 与第二个轴对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我在两个不同y轴的刻度线对齐方面面临一些问题,如下图所示,第一个以线性范围为特征,第二个以非线性范围为特征.

  HS,TMN = np.meshgrid(hs,period)r =函数(HS,TMN)cax = plt.contourf(HS,TMN,np.log10(HS),cmap = plt.cm.RdYlGn_r)ax = plt.gca()ax2 = ax.twinx()ticks2 = get_y2values(ax.get_yticks()) # 非线性函数ax2.yaxis.set_major_locator(ticker.FixedLocator(ticks))ax2.set_ylim([0, 700])ax.grid()ax.set_ylabel('Y1',fontsize = 14)ax2.set_ylabel('Y2', fontsize=14)plt.show()

更准确地说,右侧轴需要与左侧轴不同的比例.作为最终结果,想法是使左侧的刻度值与右侧的刻度值对齐(由于下面描述的非线性函数).例如:来自 Y1 的值 8.08 与 101.5 对齐;16.07 与 309.5 对齐...

需要新比例才能在新比例中插入新图.

解决方案

正如注释中所建议的那样,新秤的定义非常有效.请参考以下

如果有必要在 ax2 轴上添加新图,则需要在应用新的自定义比例之前进行绘制.

I'm facing some problems in the alignment of the ticks of two different y-axes with the first characterized by a linear range and the second by a non linear range as depicted in the following picture.

HS, TMN = np.meshgrid(hs, period)
r = function(HS, TMN)
cax = plt.contourf(HS, TMN, np.log10(HS), cmap=plt.cm.RdYlGn_r)
ax = plt.gca()
ax2 = ax.twinx()
ticks2 = get_y2values(ax.get_yticks()) # Non linear function
ax2.yaxis.set_major_locator(mpl.ticker.FixedLocator(ticks))
ax2.set_ylim([0, 700])
ax.grid()
ax.set_ylabel('Y1', fontsize=14)
ax2.set_ylabel('Y2', fontsize=14)
plt.show()

More precisely, the right axis requires a different scale from the one on the left. And as final outcome, the idea is to have ticks values on the left aligned with the ticks values on the right (due to the non-linear function depicted below). E.g.: the value 8.08 from Y1 aligned with 101.5; 16.07 aligned with 309.5...

The new scale is required in order to insert new plot in the new scale.

解决方案

As suggested in the comments the definition of a new scale works perfectly.Referring to the SegmentedScale defined at the following link, the code that worked for me is the following:

hs = np.linspace(0.1, 15, 1000) # [meters]
period = np.linspace(0.1, 35, 1000) # [seconds]

HS, TMN = np.meshgrid(hs, period)
cax = plt.contourf(HS, TMN, np.log10(HS), cmap=plt.cm.RdYlGn_r)
ax1 = plt.gca()
ax2 = ax.twinx()
ticks = get_y2values(ax1.get_yticks()) # Non linear function
ax2.set_yscale('segmented', points=ticks)

ax1.grid()
ax1.set_yticks(ax1.get_yticks())
ax2.set_yticks(ticks)
ax1.set_ylabel('Y1', fontsize=14)
ax2.set_ylabel('Y2', fontsize=14)
plt.show()

If it is necessary to add new plots on the ax2 axis, it is required to do the plot before the application of the new custom scale.

这篇关于使用非线性刻度将 twinx 与第二个轴对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:48