0

I want to create a figure that shows a background image with overlaid scatter and line plots:

The curve fit probably isn't the best you've seen. That's ok.

As you can see, the axes ticks show image coordinates. The scatter and line plot are given in image coordinates, too - which is not desired. The scatter and line plots should still be able to work (and be meaningful) without the background image. The extent is not known because this figure is used to determine the extent (interactively) in the first place.

Instead, I'd like to specify the scatter and line plots in the coordinate system shown in the background image (units m³/h and m): the transformation from image coordinates to "axis on top" coordinates would be roughly (110,475) -> (0,10) and (530,190) -> (8,40).

In principle I can see two ways of doing it:

  • specify image extent after it has been added. However, I don't see this documented anywhere; This example shows how it's done when the extent is known at the call to imshow(): Plot over an image background in python
  • add an axes on top of the image axes with twinx and twin y, where both x,x and y,y pairs are tightly coupled. I have only seen features that allow me to specify a shared x or a shared y axis, not both.
Christoph
  • 1,040
  • 3
  • 14
  • 29

1 Answers1

1

The restriction here seems to be that "The scatter and line plots should still be able to work (and be meaningful) without the background image.". This however would not imply that you cannot use the extent keyword argument.

At the time you add the image, you'd specify the extent.

plt.scatter(...)
plt.plot(...)
plt.imshow(..., extent = [...])

You can also set the extent later, if that is desired for some reason not explained in the question, i.e.

plt.scatter(...)
plt.plot(...)
im = plt.imshow(...)

im.set_extent([...])

Finally you may also decide to remove the image, and plot it again; this time with the desired extent,

plt.scatter(...)
plt.plot(...)
im = plt.imshow(...)

im.remove()
im = plt.imshow(..., extent=[...])
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thanks for pointing out that the reason why the extent is not known earlier is missing in the question. I've added that. – Christoph May 16 '18 at 19:39
  • just setting the extent after calling imshow resulted in a distorted image (narrow/tall) because the actual x extent is smaller than the y extent. From a certain perspective that might make sense, but I'd like the image to keep its aspect ratio. – Christoph May 16 '18 at 20:00
  • That would be determined by the `aspect`. You may set it to `aspect="auto"` or any other number you need. – ImportanceOfBeingErnest May 16 '18 at 20:13