Ggplot2 and facet_grid: add the highest value for each plot

I use facet_grid () to plot a breakdown into separate data groups. For each graph, I want to add the largest value of the Y axis to the corner. I tried several hacks, but it never gives the expected results. This answer partially helps me, but the value I want to add will constantly change, so I don’t see how I can apply it.

Here is a minimal example, I would like to add red numbers to the chart below:

library(ggplot2)

data <- data.frame('group'=rep(c('A','B'),each=4),'hour'=rep(c(1,2,3,4),2),'value'=c(5,4,2,3,6,7,4,5))

ggplot(data,aes(x = hour, y = value)) +
  geom_line() +
  geom_point() +
  theme(aspect.ratio=1) +
  scale_x_continuous(name ="hours", limits=c(1,4)) +
  scale_y_continuous(limits=c(1,10),breaks = seq(1, 10, by = 2))+
  facet_grid( ~ group)

enter image description here

Thank you for your help!

+4
source share
2 answers

This is a trick. If you always have fixed ranges, you can place the text manually.

library(ggplot2)

data <- data.frame('group'=rep(c('A','B'),each=4),'hour'=rep(c(1,2,3,4),2),'value'=c(5,4,2,3,6,7,4,5))

ggplot(data,aes(x = hour, y = value)) +
    geom_line() +
    geom_point() +
    geom_text(
        aes(x, y, label=lab),
        data = data.frame(
            x=Inf,
            y=Inf,
            lab=tapply(data$value, data$group, max),
            group=unique(data$group)
        ),
        vjust="inward",
        hjust = "inward"
    ) +
    theme(aspect.ratio=1) +
    scale_x_continuous(name ="hours", limits=c(1,4)) +
    scale_y_continuous(limits=c(1,10),breaks = seq(1, 10, by = 2))+
    facet_grid( ~ group)
+1
library(dplyr)
data2 <- data %>% group_by(group) %>% summarise(Max = max(value))

ggplot(data,aes(x = hour, y = value)) +
  geom_line() +
  geom_point() +
  geom_text(aes(label = Max), x = Inf, y = Inf, data2, 
            hjust = 2, vjust = 2, col = 'red') +
  theme(aspect.ratio=1) +
  scale_x_continuous(name ="hours", limits=c(1,4)) +
  scale_y_continuous(limits=c(1,10),breaks = seq(1, 10, by = 2))+
  facet_grid( ~ group)

enter image description here

+3

Source: https://habr.com/ru/post/1665210/


All Articles