2
$\begingroup$

I need to add some text to rectangles that I am using as a scale bar. I want the text right above the rectangle and centered. Here's my code:

Show[{Graphics[{Red, Rectangle[{0, 0}, {45, 15}]}, ImageSize -> 48], 
  Graphics[Text[Style["TEXT", 12, "TR", Black, Bold]]]}]

enter image description here

Desired result:

enter image description here

How can I do that?

Edit: Ideally it should also work if the text is longer than the scale bar, like so:

Graphics[{Red, Rectangle[{0, 0}, {19, 15}], 
  Text[Style["TEXT", 14, "TR", Black, Bold], {10, 22}]}, 
 ImageSize -> 19]

The bar crops some of the text: enter image description here

$\endgroup$
6
  • $\begingroup$ Add coordinates to Text like this Graphics[{Red, Rectangle[{0, 0}, {45, 15}], Text[Style["TEXT", 12, "TR", Black, Bold], {22, 20}]}, ImageSize -> 48] $\endgroup$
    – LouisB
    Oct 11 '20 at 3:17
  • $\begingroup$ That can generate problems if the text is longer than the bar. $\endgroup$
    – Rodrigo
    Oct 11 '20 at 3:28
  • $\begingroup$ ImageSize -> Large or just remove ` ImageSize -> 48` ! $\endgroup$
    – cvgmt
    Oct 11 '20 at 4:20
  • $\begingroup$ That will mess with the size and the scale bar will show up wrong. $\endgroup$
    – Rodrigo
    Oct 11 '20 at 4:23
  • $\begingroup$ Graphics[{Red, Rectangle[{0, 0}, {19, 15}], Text[Style["TEXT", Tiny, "TR", Black, Bold], {19/2, 18}]}, ImageSize -> 19] $\endgroup$
    – cvgmt
    Oct 11 '20 at 4:39
3
$\begingroup$

Add Scaled

g = Graphics[{Red, Rectangle[{0, 0}, {19, 15}], 
    Text[Style["TEXT", FontSize -> Scaled[.3], "TR", Black, 
      Bold], {19/2, 18}]}, ImageSize -> 20];
Table[Export["fig" <> ToString[i] <> ".png", g, 
  ImageSize -> i], {i, {50, 100, 150}}]
Import["fig50.png"]
Import["fig100.png"]
Import["fig150.png"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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