2016-12-29 3 views
4

私は、データのグループごとに分割された複数のプロットをプロットするためにfacet_grid()を使用しています。各プロットに対して、Y軸の最高値をコーナーに追加したい。私はいくつかのハッキングを試みましたが、それは私に期待される結果を与えることはありません。このanswerは部分的に私を助けますが、私が追加したい値は絶えず変化しているので、私はそれをどのように適用できるかわかりません。あなたの助けのためのggplot2とfacet_grid:各プロットの最高値を追加

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

ありがとう:ここ

は最小限の例ですが、私は下のグラフの赤い数字を追加したいと思います!

+1

ggplot2の外側にあるグループごとに、たとえば 'aggregate'を使用して最大値を計算します。 – Roland

+1

... geom_textのように、geom_text(aes(label = value、y = Inf、x = Inf)、aggregate(value〜group、data、max)、hjust = 2、vjust = 2、 color = "red"、fontface = 2) 'である。 – lukeA

答えて

1

これは、トリックを行います。固定範囲が常にある場合は、テキストを手動で配置できます。

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) 
3
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

+1

@RichardTelford: 'data2'は' geom_text'にのみ使われ、ポイントと行は 'data'を使います。 – Axeman

+0

申し訳ありません - あなたのソリューションは私のものと同じだと思っていましたが、私は '要約 'ではなく'突然変異 'を使用し、その後同じデータを使用しました。 –

+1

@リチャードテルフォード私はそれが数回オーバープロットされると思うが、少し奇妙に見えることがある。 – Axeman

関連する問題