1

I'm tying to overlay a scatter plot and a matrix plot, in such a way that the the relative sizes of the markersize and the boxes given in ax.matshow() do not change with scale.

For example, consider the following code:

import matplotlib.pyplot as plt
import numpy as np

ax = plt.axes()
mat = np.random.random((5,5))
ax.matshow(mat, aspect='equal')
ax.scatter([1], [2], marker='v', s=700)

This returns the following image:

enter image description here

However, let's say now I want to change the dimension of the matrix plot to (5,20). Then the code

ax = plt.axes()
mat = np.random.random((5,20))
ax.matshow(mat, aspect='equal')
ax.scatter([1], [2], marker='v', s=700)

returns the image

enter image description here


Note how the triangle I want to plot is now larger than the box shown in ax.matshow(). I would like them to scale together in a way that the triangle always fits within the matrix plot box. Any ideas on how to do this?

  • There is no automatic way. The size of the scatter triangle is determined in "points" (related to pixels), while the size of the `matshow` cells is determined to nicely fill the available space. You could draw a triangular polygon instead. – JohanC Nov 12 '21 at 18:48
  • @wikikikitiki Thank you. I see from one of your links how to get the figure size in pixels. I'm unsure of exactly how to get the width in pixels of each box in the matrix plot, though. – InertialObserver Nov 12 '21 at 19:14
  • The width of the cells is exact 1 data-unit. You need to do the calculations after creating the `matshow` and make sure the data limits aren't changed afterwards. – JohanC Nov 12 '21 at 19:19
  • @JohanC How exactly would I do that, and what do you mean by 1 data-unit? what attribute do i get from my ```ax``` object after ```ax.matshow()``` to find how it has changed the spacings? – InertialObserver Nov 12 '21 at 19:22
  • 1
    It's `ax.transData`. The *question* in [How to adjust the marker size of a scatter plot?](https://stackoverflow.com/questions/65174418/how-to-adjust-the-marker-size-of-a-scatter-plot-so-that-it-matches-a-given-radi) contains the full code (provided the xlims don't change). Alternatively, the second part of the accepted answer of [Scale matplotlib.pyplot.Axes.scatter markersize by x-scale](https://stackoverflow.com/questions/48172928/scale-matplotlib-pyplot-axes-scatter-markersize-by-x-scale) has a similar formula: `s = ((ax.get_window_extent().width / (vmax-vmin+1.) * 72./fig.dpi) ** 2)` – JohanC Nov 12 '21 at 19:32
  • @JohanC Got it. Thanks so much for your help – InertialObserver Nov 12 '21 at 19:38

0 Answers0