ファセット付きボックスプロットが必要です。プロットのx軸は量的変数であり、この情報をプロットに反映させたい。横軸のスケールはファセット間で非常に異なる。ggplot2:異なるスケールのファセットでファセットを作成するときのボックスプロットの幅が正しくありません
私の問題は、大規模なファセットの場合、ボックスの幅が非常に小さいことです。
ボックスの幅はすべてのファセットで同じですが、理想的には各ファセットのxlimによって決まるはずです。
私は2つの入力に対して感謝される:
- あなたは、これはバグであると報告されなければならないと思いますか?
- 解決策はありますか?
ありがとうございます!
備考:横座標をカテゴリ変数に変換することは1つの解決策になる可能性がありますが、いくつかの情報が失われるため完全ではありません。
最小実施例:
library(tidyverse)
c(1:4,7) %>%
c(.,10*.) %>% # Create abscissa on two different scales
lapply(FUN = function(x) {tibble(x = x, y = rnorm(50), idx = ifelse(test = x<8, yes = 'A', no = 'B'))}) %>% # Create sample (y) and label (idx)
bind_rows() %>%
ggplot(aes(x = x, y = y, group = x)) +
geom_boxplot() +
facet_wrap(~idx, scales = 'free')
結果:
面倒な溶液が最初から箱ひげ図を再描画することであろうが、これは非常に満足ではない:
draw_boxplot = function(locations, width, ymin, lower, middle, upper, ymax, idx){
local_df = tibble(locations = locations, width = width, ymin = ymin, lower = lower, middle = middle, upper = upper, ymax = ymax, idx = idx)
ggplot(data = local_df) +
geom_rect(aes(xmin = locations - width/2, xmax = locations + width/2, ymin = lower, ymax = upper), fill = 'white', colour = 'black') +
geom_segment(aes(x = locations - width/2, xend = locations + width/2, y = middle, yend = middle), size = 0.8) +
geom_segment(aes(x = locations, xend = locations, y = upper, yend = ymax)) +
geom_segment(aes(x = locations, xend = locations, y = lower, yend = ymin)) +
facet_wrap(~idx, scales = 'free_x')
}
make_boxplot = function(to_plot){
to_plot %>%
cmp_boxplot %>%
(function(x){
draw_boxplot(locations = x$x, width = x$width, ymin = x$y0, lower = x$y25, middle = x$y50, upper = x$y75, ymax = x$y100, idx = x$idx)
})
}
cmp_boxplot = function(to_plot){
to_plot %>%
group_by(idx) %>%
mutate(width = 0.6*(max(x) - min(x))/length(unique(x))) %>% #hand specified width
group_by(x) %>%
mutate(y0 = min(y),
y25 = quantile(y, 0.25),
y50 = median(y),
y75 = quantile(y, 0.75),
y100 = max(y)) %>%
select(-y) %>%
unique()
}
c(1:4,7) %>%
c(.,10*.) %>%
lapply(FUN = function(x) {tibble(x = x, y = rnorm(50), idx = ifelse(test = x<8, yes = 'A', no = 'B'))}) %>%
bind_rows() %>%
make_boxplot
結果:
一般的にボックスプロットは数値ではなくカテゴリ変数に使用します。 –
試してみてください: 'ggplot(aes(x = as.factor(x)、y = y))' – missuse
あなたの提案は次のようになります: "横座標をカテゴリ変数に変換することは一つの解決策かもしれませんが、いくつかの情報が失われてしまうため、完璧ではありません。 – konkam