繁体   English   中英

如何从 R 中的频率表创建堆积条形图?

[英]How do I create a stacked bar chart from a frequency table in R?

如果我有一张看起来像这样的表:

  V1 V2 V3 V4
A 12 10 10 10
T 13 14 13 10
G 19 08 13 10
C 12 13 17 10

其中数字是列中每个字母的频率,我将如何创建一个堆积条形图,其中列名在 x 轴上,频率是绘制的值? 我不知道如何用 ggplot2 做到这一点。 列没有名称,因为列数根据另一个函数是可变的,所以我想自动创建条形图。

我有点晚了,但这是我的看法。

txt <- "  V1 V2 V3 V4
A 12 10 10 10
T 13 14 13 10
G 19 08 13 10
C 12 13 17 10"

dat <- read.table(text = txt, h=T, row.names = 1)
dat

## with base graphics
barplot(as.matrix(dat), col = 2:5)
legend("topright", fill = 2:5, legend = rownames(dat))


## with ggplot
library(ggplot2)
library(reshape2)

# transform your data
dat2 <- dat
dat2$base <- rownames(dat)
dat2 <- melt(dat2)

# plot
ggplot(dat2, aes(fill = base, y = value, x = variable)) + geom_bar(stat = "identity")

输出以下图:

在此处输入图片说明 在此处输入图片说明

这样的事情能解决你的问题吗?

library(tidyverse)

df <- tibble(
   gene = c("A", "T", "G", "C"), 
   V1 = c(12, 13, 19, 12), 
   V2 = c(10, 14, 08, 13), 
   V3 = c(10, 13, 13, 17), 
   V4 = c(10, 10, 10, 10)
)
df
#> # A tibble: 4 x 5
#>   gene     V1    V2    V3    V4
#>   <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 A        12    10    10    10
#> 2 T        13    14    13    10
#> 3 G        19     8    13    10
#> 4 C        12    13    17    10

df_long <- df %>% 
  pivot_longer(-gene)
df_long
#> # A tibble: 16 x 3
#>    gene  name  value
#>    <chr> <chr> <dbl>
#>  1 A     V1       12
#>  2 A     V2       10
#>  3 A     V3       10
#>  4 A     V4       10
#>  5 T     V1       13
#>  6 T     V2       14
#>  7 T     V3       13
#>  8 T     V4       10
#>  9 G     V1       19
#> 10 G     V2        8
#> 11 G     V3       13
#> 12 G     V4       10
#> 13 C     V1       12
#> 14 C     V2       13
#> 15 C     V3       17
#> 16 C     V4       10

ggplot(df_long, aes(x = name, y = value, fill = gene)) +
  geom_col()

reprex 包(v0.3.0) 于 2020 年 3 月 20 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM