-2

I'm trying to display the minimum value for the category on top of each column bar. But it ends up displaying multiple values instead of the minimum.

enter image description here

ggplot(subset(new_data, device %in% "Thera_PEP"),
       aes(setting, pressure, group = setting, fill = setting)) +
  geom_col(position = "dodge",
           stat = "summary",
           fun = "min") + scale_x_continuous(breaks = seq(1, 6, 1)) + 
  scale_y_continuous(label = scales::comma) + theme_classic() + 
  ylab("Minimum Trigger Pressure") + 
  xlab("Device setting") + 
  geom_text(aes(label = min(pressure)), position=position_dodge(width=0.9), vjust=-0.25)
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    Welcome to SO, user21046947! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including attempted code (please be explicit about non-base packages), sample representative data (perhaps via `dput(head(x))` or building data programmatically (e.g., `data.frame(...)`), possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Jan 22 '23 at 22:48

1 Answers1

3

To display only the minimum value per setting you have to use stat="summary" with fun="min" if geom_text. Also, note that geom_col has no stat argument. Hence, I would suggest to switch to geom_bar.

Using some fake data based on mtcars:

new_data <- mtcars[c("cyl", "mpg")]
names(new_data) <- c("setting", "pressure")
new_data$device <- "Thera_PEP"

library(ggplot2)

ggplot(
  subset(new_data, device %in% "Thera_PEP"),
  aes(setting, pressure, group = setting, fill = setting)
) +
  geom_bar(
    position = "dodge",
    stat = "summary",
    fun = "min"
  ) +
  scale_x_continuous(breaks = seq(1, 6, 1)) +
  scale_y_continuous(label = scales::comma) +
  theme_classic() +
  ylab("Minimum Trigger Pressure") +
  xlab("Device setting") +
  geom_text(aes(label = after_stat(y)),
    stat = "summary",
    fun = "min",
    position = position_dodge(width = 0.9), vjust = -.25
  )

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51