Inserting image in corner of plot without affecting aspect ratio

I have a png image that I would like to include in the corner of a plot. It seems that there is functionality for putting images in plots, but I could not find an easy way of doing what I wanted. Below is an example:

using Plots
using Images

img = load("image.png")
x = 0:0.01:2pi
y = sin.(x)
plot(x, y)
plot!([0, 1], [0, 1], img)

This does put the image in the plot in the region x=(0, 1), y=(0, 1), but it modifies the aspect ratio of the original image such that the picture is undistorted. With some careful geometry I could deduce exactly the region I would need to include in order to not distort the aspect ratio, but I was hoping that there is a simpler way to just drop in the image centered at a given (x,y) point without doing anything to the aspect ratio. Apparently the command plot!(x, y, img) does not work. Is there a way to do this?

Hi!

There is no good way to control the image position, apparently. What you might want to do in your case is creating an inset plot:

plot(x, y)
# The bbox controls the inset position: x, y, w, h (in relative units)
plot!(img, inset=bbox(0,0,0.5,0.5), subplot=2, axes=:none, ticks=[], aspect=1)

Here is what keyword arguments do:

  • inset=bbox(0,0,0.5,0.5), subplot=2: create the inset and make sure you plot into it and not the main plot
  • axes=:none, ticks=[]: hide axes and ticks for the inset
  • aspect=1: keep aspect ratio

You will end up with something like this:

Thanks! This does seem to work, although I also needed to include the showaxis=false option in order to completely hide the axis.