Home > Mobile >  Positioning a square in ggplot
Positioning a square in ggplot

Time:08-24

I have below rectangle in my ggplot

library(ggplot2)
ggplot()  
    theme_void()  
    geom_text(aes(0,0,label='Above is a square'))  
    xlab(NULL)  
    geom_rect(aes(xmin = 1, xmax = 3, ymin = 10, ymax = 15),  fill = "blue")

enter image description here

I actually want to draw a square with smaller size, not a rectangle. I also want to place this square in the middle of the window and place the text just under that.

Is there any way to perform this?

Any pointer will be very helpful.

CodePudding user response:

Another option using coord_equal which makes the scales equal and you can define the origin with 0, which makes it maybe easier to adjust the positions of text like this:

library(ggplot2)
ggplot()   
  geom_rect(aes(xmin = 0, 
                xmax = 1, 
                ymin = 0, 
                ymax = 1,
            ), fill = "blue")  
  coord_equal()  
  theme_void()  
  geom_text(aes(0.5,-0.1,label='Above is a square'))

Created on 2022-08-22 with resulting plot showing a blue square in the middle and text below it

This mixes absolute and relative units and might need adjustments depending on the dimensions of the graphics device.

CodePudding user response:

Equal distance

You need to set equal distance in geom_rect. Currently your x-axis is of 2 units while y-axis is of 5. Also include coord_fixed(ratio = 1) to force same scale of x- and y-axis.

library(ggplot2)

ggplot()  
  theme_void()  
  geom_text(aes(12.5,9.5,label='Above is a square'))  
  xlab(NULL)  
  geom_rect(aes(xmin = 10, xmax = 15, ymin = 10, ymax = 15),  fill = "blue")  
  coord_fixed(ratio = 1)

Created on 2022-08-22 by the reprex package (v2.0.1)

Different distance

If your coordinate is fixed and cannot be changed, then use coord_fixed(ratio = 0.4) to force it into a square.

library(ggplot2)

ggplot()  
  theme_void()  
  geom_text(aes(2,9.5,label='Above is a square'))  
  xlab(NULL)  
  geom_rect(aes(xmin = 1, xmax = 3, ymin = 10, ymax = 15),  fill = "blue")  
  coord_fixed(ratio = 0.4)

Created on 2022-08-22 by the reprex package (v2.0.1)

Smaller square

You can play with the xlim and ylim parameters to generate smaller square.

library(ggplot2)
ggplot()  
  theme_void()  
  geom_text(aes(2,9.5,label='Above is a square'))  
  xlab(NULL)  
  geom_rect(aes(xmin = 1, xmax = 3, ymin = 10, ymax = 15),  fill = "blue")  
  coord_fixed(ratio = 0.4, xlim = c(-5, 8), ylim = c(4, 20))

Created on 2022-08-22 by the reprex package (v2.0.1)

Remember to also change the x and y position of geom_text to have the text right under the square.

  • Related