[英]ggplot2 and facet_grid : add highest value for each plot
I am using facet_grid() to plot multiple plot divided per groups of data. 我使用facet_grid()绘制每组数据划分的多个图。 For each plot, I want to add in the corner the highest value of the Y axis. 对于每个绘图,我想在角落添加Y轴的最高值。 I've tried several hacks but it never gives me the expected results. 我已经尝试了几次黑客攻击,但它从未给我预期的结果。 This answer partially helps me but the value I want to add will constantly be changing, therefore I don't see how I can apply it. 这个答案对我有所帮助,但我想要添加的值会不断变化,因此我看不出如何应用它。
Here is a minimal example, I'd like to add the red numbers on the graph 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)
Thanks for your help! 谢谢你的帮助!
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)
This does the trick. 这样就可以了。 If you always have fixed ranges you can position 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.