0

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?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Mew
  • 368
  • 1
  • 11

1 Answers1

0

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

Redox
  • 9,321
  • 5
  • 9
  • 26
  • Ah, so, I now realise I forgot to mention a very important detail of my use-case: I am using a custom `aspect=4/8` ratio for `imshow` to stretch the 8 x 4 grid of the example to turn it into a square. Using `aspect="auto"` works if I resize the figure manually, but that's not ideal. – Mew May 22 '23 at 12:19