How to tell a geom_rect the locations of a bar placed by geom_col

Viewed 28

I have a bar chart and I want to use a geom_rect to put a rect above the bars ...

library(tidyverse)
df<-tribble(
  ~Type,~Value,
  "X", 23,
  "Y", 33
)
df
df %>% ggplot(aes(x=Type,y=Value))+
  geom_col()+
  geom_point(aes(y=Value*1.3),color="red")

The geom_point is easy, but for a geom_rect, I need to specify xmin/xmax and I have no idea how to find these?

1 Answers

Basically a discrete scale is still a numeric scale where the categories are put at integer values, i.e. the first category is put a position 1, the second at 2, ... . To place a rect on top of the bars you could therefore convert your categories to integer positions via as.numeric(factor(Type)). These positions could then be used to set the xmin/xmax needed for geom_rect:

library(tidyverse)
df <- tribble(
  ~Type, ~Value,
  "X", 23,
  "Y", 33
)

rect_width <- .9 # default width of bars in geom_col

ggplot(df, aes(x = Type, y = Value)) +
  geom_col() +
  geom_point(aes(y = Value * 1.3), color = "red") +
  geom_rect(aes(
    xmin = as.numeric(factor(Type)) - rect_width / 2,
    xmax = as.numeric(factor(Type)) + rect_width / 2,
    ymin = Value * 1.1,
    ymax = Value * 1.5,
  ), fill = "blue")

Related