There is a thread where the question was to add an automatically labelled twinx to Matplotlib's imshow. The result was:
However, I would like the ticks on the second y-axis to be 1. manually settable and 2. aligned with the other ticks. Example output drawn in Paint:
Furthermore, I want to stretch the grid tiles so that the entire grid becomes a square, by using the imshow argument aspect=4/8.
If you set the aspect ratio and follow this thread, you get extra whitespace around the graph like in this thread. Both of them claim that the solution is to use set_adjustable('box-forced'), but this seems to have been removed. When I try it, Matplotlib says
ValueError: 'box-forced' is not a valid value for adjustable; supported values are 'box', 'datalim'
When I try box, I get:
RuntimeError: Adjustable 'box' is not allowed in a twinned Axes; use 'datalim' instead
And using datalim, the white space is not removed. How do you do this in 2023?


First, you will notice that the second y-axis is not aligned to the first one and the ticks start at the edges. So, as mentioned in one of the answers, you can align the ticks by creating ax2 again. Once that is done, you need to set the ticks and ticklabels to the numbers you want. The additional lines to be added where twinx() resides in your code is given below...