从条形图中选择性地删除条形而不更改格式 [英] Selectively drop bars from bar plot without changing formatting

查看:117
本文介绍了从条形图中选择性地删除条形而不更改格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从第一个绘图中删除一个列而不改变我的两个绘图上的酒吧的宽度或对齐方式。

I would like to drop one more column from the first plot without changing the width or alignment of the bars across my two plots. Any help is greatly appreciated.

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)

# 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)

推荐答案

我可以通过变异结果变量来选择性地删除列,因此对于您希望删除的列,它的值等于零。

I was able to selectively drop columns by mutating the outcome variable so it equals zero for column(s) you wish to drop.

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) 

这篇关于从条形图中选择性地删除条形而不更改格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆