我正在使用 facet_grid() 绘制按数据组划分的多个图。对于每个图,我想在角落添加 Y 轴的最大值。我已经尝试了几次黑客攻击,但它从来没有给我预期的结果。这个 answer 对我有部分帮助,但我想添加的值会不断变化,因此我不知道如何应用它。

这是一个最小的例子,我想在下图中添加红色数字:

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)

r - ggplot2 和 facet_grid : add highest value for each plot-LMLPHP

谢谢你的帮助!

最佳答案

这就是诀窍。如果您总是有固定的范围,您可以手动定位文本。

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)

关于r - ggplot2 和 facet_grid : add highest value for each plot,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41377236/

10-12 21:57