Align twinx with second axis with non linear scale

邮差的信 提交于 2021-02-10 15:00:59

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49874482/align-twinx-with-second-axis-with-non-linear-scale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!