[英]How to overlay two geom_bar on top of each other without alpha values
我有以下數據框:
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
目前的情節如下:
我希望Foo interaction
位於疊加層的頂部。 目前,情況並非如此。 這樣我必須使用alpha
值來減輕Bar interaction
以便Foo
變得可見。
如何強制Foo
顯示在頂部並保持Bar
在后面而不使用alpha
值?
之前已報告geom_bar填充順序未使用stat ='identity'維護 。 下面哈德利的響應( 粗體添加了強調):
使用stat =“identity”時,不會以任何方式操縱數據,因此條形將按原始數據框中的順序顯示。
在繪制之前,您可以嘗試根據因子級別順序排列數據框:
ggplot(plot_dat %>% arrange(interaction),
aes(x = sample_name, y = percent, fill = interaction)) +
geom_col(position = "identity")
這不是最有效的答案,但您可以將兩個過濾器傳遞到代碼中並單獨繪制它們。 這是我的代碼:
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.