DN1
DN1

Reputation: 218

How to plot multiple columns in r?

I have a dataset with 10 genes. I want to plot the genes along the x-axis and there to be 2 plots in 1 of the 2 scores I have for the genes.

For example my data looks like this:

Gene1            label4      label3
RP11-983P164    0.2678077   0.2119513
SLC25A20        0.2644568   0.2586816
GLS             0.2560175   0.2631010
IKZF4           0.2468294   0.2189585
NRIP3           0.2446390   0.2170968
SENP1           0.2372014   0.2724868
SLC27A6         0.2321821   0.2218227
SRFBP1          0.2293986   0.2688244
OBFC1           0.2279012   0.2187441
STEAP2          0.2239941   0.2001475

I'm looking to create a bar graph plotting both the results for label4 and label3 for each gene, but I'm struggling to find similar code examples that work this my data. I've been trying stuff like this:

df %>%
  gather("label3", "label4",-Gene1) %>%
  ggplot(aes(Gene1, label3, fill = label3)) +
  ggplot(aes(Gene1, label4, fill = label4)) +
  geom_bar(position = "dodge", stat = "identity") +
  theme_bw()

but this doesn't work at all, any help would be appreciated.

Input data:
dput(dt)
structure(list(Gene1 = c("RP11-983P164", "SLC25A20", "GLS", "IKZF4", 
"NRIP3", "SENP1", "SLC27A6", "SRFBP1", "OBFC1", "STEAP2"), label4 = c(0.267807692, 
0.264456809, 0.256017476, 0.24682942, 0.244638979, 0.237201422, 
0.232182056, 0.229398578, 0.227901191, 0.223994106), label3 = c(0.211951256, 
0.258681595, 0.263101041, 0.218958497, 0.217096806, 0.272486806, 
0.221822709, 0.268824399, 0.218744099, 0.20014748)), row.names = c(NA, 
-10L), class = c("data.table", "data.frame")

Upvotes: 2

Views: 169

Answers (2)

zx8754
zx8754

Reputation: 56004

Using pivot correctly:

pivot_longer(dt, cols = starts_with("label"),
             names_to = "Label", values_to = "Score") %>% 
  ggplot(aes(Gene1, Score, fill = Label)) +
  geom_bar(position = "dodge", stat = "identity") +
  theme_bw()

enter image description here

Upvotes: 2

NColl
NColl

Reputation: 757

Is this what you're looking for?

library(tidyverse)

df <- data.frame(structure(list(Gene1 = c("RP11-983P164", "SLC25A20", "GLS", "IKZF4",
                                      "NRIP3", "SENP1", "SLC27A6", "SRFBP1", "OBFC1", "STEAP2"), 
                            label4 = c(0.267807692, 0.264456809, 0.256017476, 0.24682942, 0.244638979, 0.237201422, 
                                       0.232182056, 0.229398578, 0.227901191, 0.223994106), 
                            label3 = c(0.211951256, 0.258681595, 0.263101041, 0.218958497, 0.217096806, 0.272486806, 
                                       0.221822709, 0.268824399, 0.218744099, 0.20014748)), 
                       row.names = c(NA, -10L), class = c("data.table", "data.frame")))

df %>%
  pivot_longer(cols=c(-Gene1)) %>%
  ggplot(., aes(Gene1, value, group=name, fill=name)) +
  geom_col(position = 'dodge')

enter image description here

Upvotes: 3

Related Questions