Ns

ggplot2-プロットの外側に注釈を付ける



Ggplot2 Annotate Outside Plot



解決:

これは、ggplot2 3.0.0で簡単になりました。これは、プロットでクリッピングを無効にできるようになったためです。次のような座標関数のclip = 'off'引数coord_cartesian(clip = 'off')またはcoord_fixed(clip = 'off')。以下に例を示します。

#データdfを生成する<- data.frame(y=c('cat1','cat2','cat3'), x=c(12,10,14), n=c(5,15,20)) # Create the plot ggplot(df,aes(x=x,y=y,label=n)) + geom_point()+ geom_text(x = 14.25, # Set the position of the text to always be at '14.25' hjust = 0, size = 8) + coord_cartesian(xlim = c(10, 14), # This focuses the x-axis on the range of interest clip = 'off') + # This keeps the labels from disappearing theme(plot.margin = unit(c(1,3,1,1), 'lines')) # This widens the right margin  

ここに画像の説明を入力してください




2番目のプロットを描く必要はありません。あなたが使用することができますプロット領域の内側または外側の任意の場所にグロブを配置するannotation_custom。グローブの配置は、データ座標の観点から行われます。 「5」、「10」、「15」が「cat1」、「cat2」、「cat3」と整列していると仮定すると、textGrobsの垂直位置が処理されます。3つのtextGrobsのy座標は次の式で与えられます。 3つのデータポイントのy座標。デフォルトでは、ggplot2は、グロブをプロット領域にクリップしますが、クリッピングはオーバーライドできます。グロブのためのスペースを作るために、関連するマージンを広げる必要があります。次の(ggplot2 0.9.2を使用)は、2番目のプロットと同様のプロットを示します。

ライブラリ(ggplot2)ライブラリ(グリッド)df = data.frame(y = c( 'cat1'、 'cat2'、 'cat3')、x = c(12,10,14)、n = c(5,15、 20))p<- ggplot(df, aes(x,y)) + geom_point() + # Base plot theme(plot.margin = unit(c(1,3,1,1), 'lines')) # Make room for the grob for (i in 1:length(df$n)) { p <- p + annotation_custom( grob = textGrob(label = df$n[i], hjust = 0, gp = gpar(cex = 1.5)), ymin = df$y[i], # Vertical position of the textGrob ymax = df$y[i], xmin = 14.3, # Note: The grobs are positioned outside the plot area xmax = 14.3) } # Code to override clipping gt <- ggplot_gtable(ggplot_build(p)) gt$layout$clip[gt$layout$name == 'panel'] <- 'off' grid.draw(gt)  

ここに画像の説明を入力してください




に基づくより単純なソリューショングリッド

require(grid)df = data.frame(y = c( 'cat1'、 'cat2'、 'cat3')、x = c(12、10、14)、n = c(5、15、20))p<- ggplot(df, aes(x, y)) + geom_point() + # Base plot theme(plot.margin = unit(c(1, 3, 1, 1), 'lines')) p grid.text('20', x = unit(0.91, 'npc'), y = unit(0.80, 'npc')) grid.text('15', x = unit(0.91, 'npc'), y = unit(0.56, 'npc')) grid.text('5', x = unit(0.91, 'npc'), y = unit(0.31, 'npc'))