Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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().