簡體   English   中英

在 ggplot2 中創建條形 plot - 放置數據框值而不是計數

[英]Create bar plot in ggplot2 - Place data frame values instead of count

我想使用 ggplot2 將此數據放在條形 plot 上

在此處輸入圖像描述

其中“Clades”列將放置在 X 軸上,每列的值(例如 19A 的值)將放置在 Y 軸上

我正在嘗試這樣的事情:

cols = as.vector(names(snv_data)[2:19])
ggplot(df, aes(x=cols)) + geom_bar()

但我不斷得到這個:

在此處輸入圖像描述

我是 ggplot2 的新手,所以非常歡迎任何幫助!

我這樣做是為了嘗試獲得 7 個圖(每列一個,例如 19A、20A、20B 等),其中每個 plot 將在 X 軸上具有 Clade,並且每列中的每個值作為“計數” Y軸

輸入:

structure(list(Clades = c("C.T", "A.G", "G.A", "G.C", "T.C", 
"C.A", "G.T", "A.T", "T.A", "T.G", "A.C", "C.G", "A.del", "TAT.del", 
"TCTGGTTTT.del", "TACATG.del", "AGTTCA.del", "GATTTC.del"), `19A` = c(413, 
93, 21, 0, 49, 9, 238, 13, 3, 1, 0, 4, 1, 0, 0, 0, 0, 0), `20A` = c(7929, 
1920, 1100, 419, 1025, 124, 3730, 124, 22, 45, 64, 17, 8, 19, 
23, 39, 0, 0), `20B` = c(5283, 1447, 2325, 1106, 336, 117, 946, 
137, 35, 53, 123, 11, 9, 10, 21, 1, 0, 0), `20E (EU1)` = c(13086, 
1927, 650, 1337, 1864, 96, 2967, 243, 69, 92, 115, 1486, 27, 
5, 0, 1, 0, 0), `20I (Alpha, V1)` = c(71142, 12966, 12047, 15587, 
14935, 15382, 11270, 12211, 5284, 4273, 430, 99, 5674, 4536, 
4974, 4592, 0, 0), `20J (Gamma, V3)` = c(2822, 654, 883, 409, 
501, 213, 843, 399, 203, 27, 429, 198, 1, 0, 197, 0, 0, 0), `21J (Delta)` = c(166003, 
49195, 26713, 1399, 25824, 15644, 95967, 2011, 329, 11034, 716, 
21087, 10532, 198, 0, 14, 9809, 10503)), class = "data.frame", row.names = c("C.T", 
"A.G", "G.A", "G.C", "T.C", "C.A", "G.T", "A.T", "T.A", "T.G", 
"A.C", "C.G", "A.del", "TAT.del", "TCTGGTTTT.del", "TACATG.del", 
"AGTTCA.del", "GATTTC.del"))

正如 cazman 在評論中所說,您需要獲取長格式的數據才能與 ggplot2 (有效地)一起使用。

首先,使用pivot_longer() ,然后使用 ggplot2:

library(tidyverse)
dat %>% 
    pivot_longer(-Clades) %>% 
    ggplot(aes(x=Clades, y=value, fill=name)) + 
    geom_col()

在此處輸入圖像描述

要添加到前面的答案,這里是如何使用facet_wrap()

df <- df %>%
  pivot_longer(-Clades)

ggplot(data = df,
       aes(x = Clades,
           y = value)) +
  geom_bar(aes(fill = Clades),
           stat = 'identity') +
  facet_wrap(~name, scales = 'free_y') +
  theme(axis.text.x = element_blank())

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM