imshow with twinx that is also aligned with tiles

106 Views Asked by At

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?

1

There are 1 best solutions below

1
Redox On

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...

ax2 = ax1.twinx()

## Create same plot with ax2
ax2.imshow(twoDim, cmap='Purples', interpolation='nearest', aspect='auto')
ax2.set_yticks(np.arange(0,twoDim.shape[0],1))  ## Set ax2 ticks
## ticklabels set to whatever you want, just make sure the counts of ticks and ticklables match
ax2.set_yticklabels(np.arange(3,(twoDim.shape[0]+1)*3,3))  

enter image description here