私はこれを達成する最も簡単な方法は、あなたがプロットを作成する前にデータを準備することだと思います。私は大陸与えstuff.dat
からリンゴ・バナナ・インデックスを計算する関数abi()
定義:
abi <- function(cont) {
with(stuff.dat,
num[continent == cont & stuff == "apples"]/num[continent == cont & stuff == "bananas"]
)
}
をそして私は必要なすべてのデータをデータフレームを作成します。私ができる、今
conts <- levels(stuff.dat$continent)
abi_df <- data.frame(continent = conts,
yf = aggregate(num ~ continent, sum, data = stuff.dat)$num + 5,
abi = round(sapply(conts, abi), 1))
プロットにその情報を追加します。
library(ggplot2)
ggplot(stuff.dat, aes(x = continent, y = num, fill = stuff)) +
geom_col() +
geom_text(position = position_stack(vjust = 0.5), aes(label = num)) +
geom_text(data = abi_df, aes(y = yf, label = paste0("f = ", abi), fill = NA))
にfill = NA
を追加するとハックが発生し、警告が表示されます。しかし、fill
が設定されていない場合、プロットは失敗し、stuff
が見つからないというメッセージが表示されます。私もfill = stuff
をggplot()
からgeom_col()
に移動しようとしましたが、これはバーの中のテキストラベルのy座標を壊します。これにはよりクリーンな解決策があるかもしれませんが、私はそれをまだ見つけていません。
追加の凡例を追加することは残念ながら、プロット領域の外にテキストを簡単に追加できないため、些細なことではありません。これには実際には2つのステップが必要です。最初にannotation_custom()
を使用してテキストを追加します。テキストを表示するには、クリッピングをオフにする必要があります(たとえば、hereを参照)。あなたは、通常のバープロットは、そのテキストを必要としないことを知っている
p <- ggplot(stuff.dat, aes(x = continent, y = num, fill = stuff)) +
geom_col() +
geom_text(position = position_stack(vjust = 0.5), aes(label = num)) +
geom_text(data = abi_df, aes(y = yf, label = paste0("f = ", abi), fill = NA)) +
guides(size = guide_legend(title = "f: ABI", override.aes = list(fill = 1))) +
annotation_custom(grob = textGrob("f: ABI\n(Apple-\nBanana-\nIndex",
gp = gpar(cex = .8), just = "left"),
xmin = 3.8, xmax = 3.8, ymin = 17, ymax = 17)
# turn off clipping
library(grid)
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
:これは可能な解決策とは?この数字は把握するのが難しく、この追加情報が必要になります – PoGibas