最初にいくつかの背景。ggplot2 を使用してウォーターフォール プロットを作成しようとしています。トリックを行う次の関数を作成しました。ただし、 geom_text ラベルにユーザー指定の書式設定関数を提供しようとすると、小さな問題が発生します。
plotIt<-function()
{
require(ggplot2)
require(scales)
# Define formatting functions
formatter<-function(x, ...) format(x, big.mark = ' ', trim = TRUE, scientific = FALSE, ...)
strwr<-function(x) gsub(" ", "\n", x)
# Build data frame to plot
mydf<-structure(list(Description = structure(1:6, .Label = LETTERS[1:6], class = "factor"),
change = c(0.86, 0.14, 0.08, -0.05, -0.03, 1.00),
id = 1:6,
end = c(0.86, 1.00, 1.08, 1.03, 1.00, 0.00),
start = c(0, 0.86, 1.00, 1.08, 1.03, 1.00),
type = structure(c(2L, 2L, 2L, 1L, 1L, 2L), .Label = c("Neg", "Pos"), class = "factor")),
.Names = c("Description", "change", "id", "end", "start", "type"),
row.names = LETTERS[1:6], class = "data.frame")
# Plot it
ggplot(mydf, aes(Description, fill = type)) +
geom_rect(aes(x = Description, xmin = id - 0.45, xmax = id + 0.45, ymin = end, ymax = start)) +
scale_y_continuous(labels = formatter) +
scale_x_discrete("", breaks = levels(mydf$Description), labels = strwr(levels(mydf$Description))) +
geom_text(aes(x = id, y = end, label = formatter(change)), vjust = 1, size = 3)
}
この関数を呼び出すと、次のエラー メッセージが生成されます。
eval(expr、envir、enclos)のエラー:関数「フォーマッター」が見つかりませんでした
原因は、最後の行 geom_text の label = formatter(change) コードです。label = comma(change) に置き換えると、すべて正常に動作します。「コンマ」関数は scales パッケージから来ています。要するに:
geom_text(aes(x = id, y = end, label = comma(change)), vjust = 1, size = 3)
動作しますが
geom_text(aes(x = id, y = end, label = formatter(change)), vjust = 1, size = 3)
ではない。
出力は次のようになります。
geom_text が独自の書式設定関数を受け入れないのはなぜですか? 単純なことだと思いますが、見えません。