gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:30:52 26 4
gpt4 key购买 nike

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

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

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

谢谢你的帮助!

最佳答案

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com