Home > other >  Create bar plot in ggplot2 - Place data frame values instead of count
Create bar plot in ggplot2 - Place data frame values instead of count

Time:01-15

I'd like to place this data onto a bar plot using ggplot2

enter image description here

where the column "Clades" would be placed on the X axis and the values from each column (such as the values of 19A, for example) would be place on Y axis

I'm trying something like this:

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

But I keep getting this:

enter image description here

I'm new to ggplot2 so any help is very welcome!

I'm doing this to try and get 7 plots (one for each column such as 19A, 20A, 20B, etc) where each plot would have the Clades on the X-axis and each value from each column as the "counts" on the Y-axis

dput:

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

CodePudding user response:

To add to the previous answer, here is how you can get 7 plots (1 for each Clade, which is how I interpreted the question) using 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())

enter image description here

CodePudding user response:

As cazman said in the comments, you need to get your data in long form for it to work with ggplot2 (efficiently).

First, use pivot_longer(), and then use ggplot2:

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

enter image description here

  •  Tags:  
  • Related