【问题标题】:ggplot2 and facet_grid : add highest value for each plotggplot2 和 facet_grid :为每个图添加最高值
【发布时间】:2016-12-29 09:57:05
【问题描述】:

我正在使用 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)

感谢您的帮助!

【问题讨论】:

  • 计算 ggplot2 之外的每个组的最大值,例如,使用 aggregate
  • ... 或在 geom_text 调用中执行,例如 geom_text(aes(label=value, y=Inf, x=Inf), aggregate(value~group,data,max), hjust=2, vjust=2, color="red", fontface=2)

标签: r ggplot2


【解决方案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)

【讨论】:

  • @RichardTelford:data2只用于geom_text,点和线还是用data
  • 抱歉 - 我认为您的解决方案与我的相同 - 但我使用了 mutate 而不是 summarise,然后始终使用相同的数据。
  • @RichardTelford 我认为这会多次绘制数字,最终看起来有点奇怪。
【解决方案2】:

这可以解决问题。如果你总是有固定的范围,你可以手动定位文本。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 2013-03-29
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多