如何让 ggplot2 在我的翻转条形图中显示计数?

How can I get ggplot2 to display the counts in my flipped bar plot?

我有以下示例数据集:

row gene    Type    PercID  Count
1   AAC     MS  0   0
71  AAC     NDA 99.66   17
2   ABC superfamily ATP binding cassette transporter    MS  0   0
72  ABC superfamily ATP binding cassette transporter    NDA 98.5    7
3   acetyltransferase   MS  0   0
73  acetyltransferase   NDA 100 12
4   AcrA    MS  94.6    6
74  AcrA    NDA 0   0
5   AcrB    MS  96  11
75  AcrB    NDA 0   0

我添加了行列以生成唯一的行,以响应我收到的有关行名称必须唯一的错误。我将零值转换为 NA 以使我的色标仅显示有效值(在本例中为 90-100)。

我正在使用这段代码来创建情节:

library(ggplot2)
library(viridis)

mydata = read.csv("Mydata.csv", quote = "", fileEncoding = "UTF-8-BOM")

mydata2 = mydata
mydata2[, 4:5][mydata2[, 4:5] == 0] <- NA

ggplot(mydata2, aes(x = gene, y = Count, fill = PercID))+
geom_bar(position = position_fill(reverse = TRUE), stat = 'identity')+
facet_wrap(~ Type)+
coord_flip()+
scale_x_discrete(limits = rev(levels(mydata2$gene)))+
scale_fill_viridis(discrete = FALSE, name = "Percent Identity", option = 'plasma')+
theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

这会生成一个所有条形长度相同的图:

我希望我的条形图反映数据中 Count 列的实际计数,以便它们的长度可变。

我曾尝试删除 stat = 'identity' 但这给了我这个错误消息 Error: stat_count() can only have an x or y aesthetic. 我也尝试删除 y = Count 但后来我得到一个错误,我需要一个 y 美学。

如何让我的绘图显示反映 Count 值的条形长度?

不太确定你想要的情节是什么,在这种情况下,每个方面的每个基因只有一个值,所以不需要调整位置。

所以可能是这样的:

ggplot(mydata2, aes(x = gene, y = Count, fill = PercID))+
geom_bar(stat = 'identity')+
facet_wrap(~ Type)+
coord_flip()+
scale_x_discrete(limits = rev(levels(mydata2$gene)))+
scale_fill_viridis(discrete = FALSE, name = "Percent Identity", option = 'plasma')+
theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())