5

多数のヒストグラムを作成しており、グラフの上部に注釈を追加したいと考えています。for ループを使用してこれらをプロットしているため、ylim がグラフごとに変化しても、注釈を上部に配置する方法が必要です。ループ内の各グラフの ylim を保存できれば、現在のグラフに基づいて注釈の y 座標を変化させることができます。注釈に含める y の値は、ループが繰り返し処理されるにつれて動的に変化する必要があります。私の問題を示すサンプルコードを次に示します (注釈がどのように移動するかに注意してください。各グラフの ylim に基づいて変更する必要があります)。

library(ggplot2)

cuts <- levels(as.factor(diamonds$cut))

pdf(file = "Annotation Example.pdf", width = 11, height = 8,
    family = "Helvetica", bg = "white")

for (i in 1:length(cuts)) {
  by.cut<-subset(diamonds, diamonds$cut == cuts[[i]])
  print(ggplot(by.cut, aes(price)) +
    geom_histogram(fill = "steelblue", alpha = .55) +
  annotate ("text", label = "My annotation goes at the top", x = 10000 ,hjust = 0, y = 220, color = "darkred"))
}    
dev.off()
4

2 に答える 2

9

ggplotプロット範囲を変更せずに、その位置で使用Infして、プロット範囲の極値を表します。そのためy、注釈の値を に設定できInfvjustパラメータを調整して位置合わせを改善することもできます。

...
print(ggplot(by.cut, aes(price)) +
      geom_histogram(fill = "steelblue", alpha = .55) +
      annotate("text", label = "My annotation goes at the top", 
               x = 10000, hjust = 0, y = Inf, vjust = 2, color = "darkred"))
...

の場合i<-2、これは次のようになります。

ここに画像の説明を入力

于 2012-06-13T18:13:45.013 に答える
1

もっときちんとした方法があるかもしれませんが、最大カウントを取得し、それを使用しyて注釈呼び出しで設定できます。

for (i in 1:length(cuts)) {

  by.cut<-subset(diamonds, diamonds$cut == cuts[[i]])

  ## get the cut points that ggplot will use. defaults to 30 bins and thus 29 cuts
  by.cut$cuts <- cut(by.cut$price, seq(min(by.cut$price), max(by.cut$price), length.out=29))

  ## get the highest count of prices in a given cut.
  y.max <- max(tapply(by.cut$price, by.cut$cuts, length))

  print(ggplot(by.cut, aes(price)) +
    geom_histogram(fill = "steelblue", alpha = .55) +
    ## change y = 220 to y = y.max as defined above
    annotate ("text", label = "My annotation goes at the top", x = 10000 ,hjust = 0, y = y.max, color = "darkred"))
}  
于 2012-06-13T17:11:57.510 に答える