2017-05-18 5 views
1

2つのプロット間でバーの幅やアライメントを変更せずに、最初のプロットからもう1つの列を削除したいとします。どんな助けでも大歓迎です。フォーマットを変更せずにバープロットからバーを選択的にドロップする

theme_min <- 
    theme(
    panel.grid.minor = element_blank(), 
    panel.grid.major = element_blank(), 
    panel.background = element_blank(), 
    panel.border = element_blank(), 
    axis.line = element_line(colour = "black") 
) 

# display 2 of 4 columns 
mtcars %>% 
    mutate(
    am = factor(am, labels = c("auto", "manual")), 
    vs = factor(vs, labels = c("V", "S")) 
) %>% 
    filter(
    am == "auto" 
) %>% 
    ggplot(aes(x = am, y = mpg, fill = vs)) + 
    geom_col(position = position_dodge()) + 
    scale_y_continuous(limits = c(0,35)) + 
    theme_min + 
    scale_x_discrete(drop = FALSE) 

2 of 4 bars

# display 1 of 4 columns 
mtcars %>% 
    mutate(
    am = factor(am, labels = c("auto", "manual")), 
    vs = factor(vs, labels = c("V", "S")) 
) %>% 
    filter(
    am == "auto", 
    vs == "V" 
) %>% 
    ggplot(aes(x = am, y = mpg, fill = vs)) + 
    geom_col(position = position_dodge()) + 
    scale_y_continuous(limits = c(0,35)) + 
    theme_min + 
    scale_x_discrete(drop = FALSE) + 
    scale_fill_discrete(drop = FALSE) 

1 of 4 bars displayed, but width is out of sync with image 1

+2

推奨重複が[常にヒストグラムをかわす](http://stackoverflow.com/q/10149571/903061)、[ggplot2に同じバー幅(http://stackoverflow.com/q/24304642/903061)、[ゼロカウントドッジド棒グラフをドロップしない](http://stackoverflow.com/q/10326729/903061)... – Gregor

答えて

1

私は選択それはあなたがドロップしたい列(複数可)のためにゼロに等しいので、結果変数を変異させることによって、列をドロップすることができました。

mtcars %>% 
    mutate(
    am = factor(am, labels = c("auto", "manual")), 
    vs = factor(vs, labels = c("V", "S")) 
) %>% 
    filter(am == "auto") %>% 
    # mutate to drop bar while maintaining bar formatting 
    mutate(mpg = ifelse(vs == "S", mpg == 0, mpg)) %>% 
    ggplot(aes(x = am, y = mpg, fill = vs)) + 
    geom_col(position = position_dodge()) + 
    scale_y_continuous(limits = c(0,35)) + 
    scale_x_discrete(drop = FALSE) 

one bar plot

関連する問題