Ask Your Question
0

How can I create a stacked barplot with equal heights using pre-normalized relative abundance data in ggplot2?

asked 2021-10-01 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-12-29 16:00:00 +0000

devzero gravatar image

To create a stacked barplot with equal heights using pre-normalized relative abundance data in ggplot2, you can use the position_fill() function. Here's an example code:

library(ggplot2)

# create sample data
data <- data.frame(sample = c("Sample 1", "Sample 2", "Sample 3"),
                   taxon1 = c(0.25, 0.5, 0.1),
                   taxon2 = c(0.1, 0.2, 0.3),
                   taxon3 = c(0.3, 0.1, 0.2))

# convert data from wide to long format
data_long <- tidyr::gather(data, key = "taxon", value = "abundance", -sample)

# create ggplot object
ggplot(data_long, aes(x = sample, y = abundance, fill = taxon)) +
  geom_bar(stat = "identity", position = position_fill()) +
  scale_y_continuous(limits=c(0, 1)) +
  labs(title = "Relative Abundance",
       x = "Sample",
       y = "Abundance")

In this code, we first create a sample dataset with pre-normalized relative abundance data for three taxa in three samples. We then convert the data from wide to long format using the gather() function from the tidyr package. Finally, we create a ggplot object with geom_bar() and use position_fill() to stack the bars and ensure they have equal heights. We also set the y-axis limits to be between 0 and 1, and add a title, x-label, and y-label to the plot using labs().

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-01 11:00:00 +0000

Seen: 9 times

Last updated: Dec 29 '22