それで、しばらくの間、これについて考えていました。基本的に、新しいプリミティブを作成するときは、通常、次の組み合わせを記述します。
- 層 関数
- stat- ggproto 、
- geom- ggproto
レイヤー関数のみがユーザーに表示される必要があります。プリミティブを作成するためにデータを変換する新しい方法が必要な場合にのみ、stat-ggprotoを記述する必要があります。また、作成する新しいグリッドベースのグラフィックがある場合にのみ、 geom-ggprotoを作成する必要があります。
この場合、基本的に既存のレイヤー関数をコンポストするため、新しい ggprotos を記述する必要はありません。新しいlayer-functionを書くだけで十分です。このレイヤー関数は、既に使用している 3 つのレイヤーを作成し、パラメーターを意図したとおりにマッピングします。この場合:
- Layer1 –
geom_errorbar
とstat_boxplot
– を使用してエラーバーを取得します
- Layer2 –
geom_boxplot
およびstat_boxplot
- を使用して箱ひげ図を作成します
- Layer3 - users
geom_label
およびstat_summary
- ボックスの中央に平均値を持つテキスト ラベルを作成します。
もちろん、これらすべてを一度に実行する新しいstat-ggprotoと新しいgeom-ggprotoを作成することもできます。または、堆肥化stat_summary
して 1 つにしstat_boxplot
、3 つのgeom-protosも同様に 1 つのレイヤーでこれを行います。しかし、効率の問題がない限り、ほとんど意味がありません。
とにかく、ここにコードがあります:
geom_myboxplot <- function(formula = NULL, data = NULL,
stat = "boxplot", position = "dodge",coef=1.5,
font = "sans", fsize = 18, width=0.6,
fun.data = NULL, fun.y = NULL, fun.ymax = NULL,
fun.ymin = NULL, fun.args = list(),
outlier.colour = NULL, outlier.color = NULL,
outlier.shape = 19, outlier.size = 1.5,outlier.stroke = 0.5,
notch = FALSE, notchwidth = 0.5,varwidth = FALSE,
na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE,...) {
vars <- all.vars(formula)
response <- vars[1]
factor <- vars[2]
mymap <- aes_string(x=factor,y=response)
fun_med <- function(x) {
return(data.frame(y = median(x), label = round(median(x), 3)))
}
position <- position_dodge(width)
l1 <- layer(data = data, mapping = mymap, stat = StatBoxplot,
geom = "errorbar", position = position, show.legend = show.legend,
inherit.aes = inherit.aes, params = list(na.rm = na.rm,
coef = coef, width = width, ...))
l2 <- layer(data = data, mapping = mymap, stat = stat, geom = GeomBoxplot,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(outlier.colour = outlier.colour, outlier.shape = outlier.shape,
outlier.size = outlier.size, outlier.stroke = outlier.stroke,
notch = notch, notchwidth = notchwidth, varwidth = varwidth,
na.rm = na.rm, ...))
l3 <- layer(data = data, mapping = mymap, stat = StatSummary,
geom = "label", position = position, show.legend = show.legend,
inherit.aes = inherit.aes, params = list(fun.data = fun_med,
fun.y = fun.y, fun.ymax = fun.ymax, fun.ymin = fun.ymin,
fun.args = fun.args, na.rm=na.rm,family=font,size=fsize/3,vjust=-0.1,...))
return(list(l1,l2,l3))
}
これにより、カスタマイズした箱ひげ図を次のように作成できます。
ggplot(mpg) +
geom_myboxplot( hwy ~ class, font = "sans",fsize = 18)+
theme_grey(base_family = "sans",base_size = 18 )
そして、それらは次のようになります。

注: 実際にはこのlayer
関数を使用する必要はありませんでした。代わりに元のstat_boxplot
、geom_boxplot
、およびstat_summary
呼び出しを使用することもできました。しかし、カスタムボックスプロットからそれらを制御できるようにしたい場合は、すべてのパラメーターを入力する必要があったため、少なくとも機能ではなく構造の観点からは、この方法の方が明確だったと思います. そうではないかもしれませんが、それは好みの問題です...
また、私は見栄えの良いフォントを持っていません。しかし、それを追跡してインストールする気がしませんでした。