如何在没有alpha值的情况下彼此叠加两个geom_bar

时间:2018-12-12 03:18:12

标签: r ggplot2

我有以下数据框:

library(tidyverse)

plot_dat <- structure(list(sample_name = c("YY", "XX", "YY", 
"XX"), interaction = c("Foo interaction", "Foo interaction", 
"Bar interaction", "Bar interaction"), percent = c(9.54760559277962, 
1.21705741166346, 58.1631385457859, 13.6359995314219)), row.names = c(NA, 
-4L), .Names = c("sample_name", "interaction", "percent"), class = c("tbl_df", 
"tbl", "data.frame"))

plot_dat
#> # A tibble: 4 x 3
#>   sample_name interaction     percent
#>   <chr>       <chr>             <dbl>
#> 1 YY          Foo interaction    9.55
#> 2 XX          Foo interaction    1.22
#> 3 YY          Bar interaction   58.2 
#> 4 XX          Bar interaction   13.6

我想要做的是创建一个相互重叠的条形图。我有以下代码:

plot_dat$interaction <- factor(plot_dat$interaction, 
                               levels = c("Bar interaction", "Foo interaction") )

p <- ggplot(plot_dat, 
            aes(x = sample_name, y = percent, fill = interaction, 
                color = interaction, alpha = interaction)) +
  geom_bar(stat = "identity", position = "identity") +
  scale_alpha_manual(values = c(0.2, 1))
p

当前情节如下:

enter image description here

我希望Foo interaction位于覆盖图的顶部。 目前不是这样。这样,我必须使用alpha值来减轻Bar interaction的亮度,以使Foo可见。

如何不使用Foo值而强制Bar出现在顶部并将alpha留在后面?

2 个答案:

答案 0 :(得分:2)

以前在geom_bar fill order not maintained with stat='identity'处有报道。 Hadley的回应如下(为强调起见,添加了粗体):

  

使用stat =“ identity”,不会以任何方式处理数据,因此   条将按顺序显示在原始数据框中

您可以在绘制之前尝试根据因子级别顺序排列数据框:

ggplot(plot_dat %>% arrange(interaction), 
       aes(x = sample_name, y = percent, fill = interaction)) + 
  geom_col(position = "identity")

plot

答案 1 :(得分:1)

这不是最有效的答案,但是您可以将两个过滤器传递到代码中并分别进行绘制。这是我的有效代码:

library(tidyverse)

plot_dat <- structure(list(sample_name = c("YY", "XX", "YY", "XX"),
                       interaction = c("Foo interaction",
                                       "Foo interaction",
                                       "Bar interaction",
                                       "Bar interaction"),
                       percent = c(9.54760559277962,
                                   1.21705741166346,
                                   58.1631385457859,
                                   13.6359995314219)),
                  row.names = c(NA, -4L),
                  .Names = c("sample_name", "interaction", "percent"),
                  class = c("tbl_df", "tbl", "data.frame"))

plot_dat

plot_dat$interaction <- factor(plot_dat$interaction, levels = c("Foo interaction", "Bar interaction") )


cond1 <- plot_dat$interaction == 'Foo interaction'
cond2 <- plot_dat$interaction == 'Bar interaction'

ggplot(plot_dat[cond2,],
   aes(x=sample_name, y=percent, fill=interaction)) +
  geom_bar(stat='identity') +
  geom_bar(mapping=aes(x=plot_dat$sample_name[cond1],
                   y=plot_dat$percent[cond1],
                   fill=plot_dat$interaction[cond1]),
       stat='identity')

Here's the output of the graph.