0

I'm trying to create a boxplot in ggplot2 from a data frame, which contains information about count data from multiple samples. In my case, for each of 6 samples, a count is recorded for each gene.

So it would look like this:

df <- data.frame(sample(c(1:100), 20, replace = T), sample(c(1:100), 20, replace = T),
                 sample(c(1:100), 20, replace = T), sample(c(1:100), 20, replace = T),
                 sample(c(1:100), 20, replace = T), sample(c(1:100), 20, replace = T))
names(df) <- paste0("Sample-", c(1:6))
rownames(df) <- paste0("Gene-", c(1:20))

Here's what I've tried:

bp <- ggplot(df, aes(x = names(df), y = )) + geom_boxplot()

but I have 0 idea what to put for the y value. Literally no clue. I'm pretty sure I'm not even indicating the x-axis properly. I'd appreciate some help with this very basic problem. I'm sorry for such a simple question.

2
  • 1
    Are you trying to create a different boxplot for each sample? Commented Jun 7, 2019 at 0:32
  • @heds1: Yes, but want to plot them all on the same chart Commented Jun 7, 2019 at 0:36

2 Answers 2

2

ggplot works best when data are in tidy, "long" format as opposed to "wide" format. You can get samples into one column and their values into another using tidyr::gather:

library(tidyverse)

set.seed(1001) # for reproducible example data
# generate df here as in your question

df %>% 
  gather(Sample, Count) %>% 
  ggplot(aes(Sample, Count)) + 
  geom_boxplot()

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I'm downloading the tidyverse library right now. Will try it in a few minutes. What does the %>% signify?
tidyverse is just a quick way to load several related packages that are often used together. It isn't always necessary if you only need one or two (tidyr and ggplot2 in this case). %>% is the pipe.
1

Like this?

library(tidyverse)
df2 <- df %>% 
  gather(sample, value)

ggplot(df2, aes(sample, value)) +
  geom_boxplot() + coord_flip()

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.