Say I am creating a plot with a black rectangle on it. The position of the rectangle is specified by the canvas coordinates {x1,y1} of the lower left corner and {x2,y2} of the upper right corner.

{x1,y1}={0.5, -1.02};
{x2,y2}={2.5, -0.3};
plot = Show[
  Plot[Sin[x], {x, 0, 2 \[Pi]}, Frame -> True, ImageSize -> {Automatic,400}],
  Graphics[{Black, Rectangle[{x1,y1}, {x2,y2}]}]

enter image description here

After I export the plot with

Export[FileNameJoin[{$HomeDirectory, "Desktop", "plot_test.png"}], plot]

the position of the black rectangle in the image can be described by pixel positions of the lower left and top right corners.

Is there a way to calculate the pixel positions?

For ImagePadding -> 0, the question is simple, since the origin of the plot canvas and the image align. However, I don't know how to calculate the size of the image padding in canvas coordinates.

So far my workaround requires saving the image and then reloading it into mma, getting pixel info on the canvas origin and another point to finally calculate linear fits for conversion between coordinates and pixels. I would prefer to automate this.


1 Answer 1


You can wrap your Rectangle in an Annotation wrapper, and then use Rasterize to find the pixel positions of the annotated object:

{x1, y1} = {0.5, -1.02};
{x2, y2} = {2.5, -0.3};
plot = Show[
    Plot[Sin[x],{x,0,2 \[Pi]},Frame->True,ImageSize->{Automatic,400}],

Rasterize[plot, "Regions"]

{{None, "FOO"} -> {{82.1124, 244.665}, {269.503, 367.461}}}

The specification is $\left\{\left\{x_{\min },y_{\min }\right\},\left\{x_{\max },y_{\max }\right\}\right\}$ where the $y$ coordinate runs from top to bottom, mirroring the coords attribute of HTML.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.