首页 > 解决方案 > 如何让 ggplot2 显示翻转条形图中的计数?

问题描述

我有以下示例数据集:

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但是我得到了一个我需要美学的错误。

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

标签: rggplot2geom-bar

解决方案


不太确定您的预期情节是什么,在这种情况下,每个方面的每个基因只有一个值,因此无需调整位置。

所以可能是这样的:

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

在此处输入图像描述


推荐阅读