尝试使用这样的方面并巧妙地创建一个引用变量来创建两个变量并使用ggplot2 和一些tidyverse 函数绘制它们:
library(ggplot2)
library(tidyverse)
#Data
df %>% rownames_to_column("id") %>%
pivot_longer(-id) %>%
mutate(Flag=name %in% c('Positive','Negative')) %>%
ggplot(aes(x=Flag,y=value,fill=name))+
geom_bar(stat = 'identity')+
facet_grid(id~., switch = "y") +
scale_fill_manual(values = c("red", "tomato", "cyan3"), name = "") +
coord_flip() +
theme_classic() +
theme(panel.spacing = unit(0, "points"),
strip.background = element_blank(),
axis.text.y = element_blank(),
axis.ticks.length.y = unit(0, "points"),
axis.title = element_blank(),
strip.placement = "outside",
strip.text = element_text(),
legend.position = "bottom",
panel.grid.major.x = element_line())
输出:
更新:为了获得所需的顺序,您可以创建一个虚拟数据来对标签进行排序,然后将 id 变量格式化为因子。代码如下:
#Auxiliar data
levs <- df %>% rownames_to_column("id") %>%
pivot_longer(-id) %>%
filter(name=='Positive') %>%
arrange(desc(value))
#Data
df %>% rownames_to_column("id") %>%
pivot_longer(-id) %>%
mutate(Flag=name %in% c('Positive','Negative'),
id=factor(id,levels = levs$id,ordered = T)) %>%
ggplot(aes(x=Flag,y=value,fill=name))+
geom_bar(stat = 'identity')+
facet_grid(id~., switch = "y") +
scale_fill_manual(values = c("red", "tomato", "cyan3"), name = "") +
coord_flip() +
theme_classic() +
theme(panel.spacing = unit(0, "points"),
strip.background = element_blank(),
axis.text.y = element_blank(),
axis.ticks.length.y = unit(0, "points"),
axis.title = element_blank(),
strip.placement = "outside",
strip.text = element_text(),
legend.position = "bottom",
panel.grid.major.x = element_line())
输出: