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()
.
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
Asked: 2021-10-01 11:00:00 +0000
Seen: 9 times
Last updated: Dec 29 '22
How can you create an OpenGL plot without relying on external libraries, starting from scratch?
How can I use iText7 to create a PDF that includes a pie chart?
How can I create a monitor in Datadog that includes multiple resources' metrics in one monitor?
Create a regular expression for the following format.
How to create GS1-128 using ZXing.Net?
Is it advisable to create event handlers in a separate method rather than inline all the time?
How to implement a leaderboard in Flutter?
How to create a plot using mplfinance and PyQt5 that includes a volume graph?