'Is there an easy way to make an horizontal single stacked Barplot with R?
I'd appreciate if anyone could help me with making a single stacked Barplot with R.
cell_type Percentage
CD20 B cells 15.00
CD4 T cells 25.00
Other cells 60.00
Here is a small example of data to plot.
This is what I used, but cannot modify too much.
p1 <- ggplot(Data, aes(x = "", y = percentage, fill = cell_type))
p1
p2 <- p1 + geom_col() p2
Many thanks in advance for your help.
Solution 1:[1]
Use coord_flip to make it horizontal, to adjust bar thickness specify the width argument, and you can set fill colors manually using scale_fill_manual:
library(ggplot2)
df %>%
ggplot(aes(x = "", y = Percentage, fill = cell_type)) +
geom_col(width = .25) +
scale_fill_manual(values = c("black", "#039dfc", "yellow")) +
coord_flip()
If you have multiple bars then you will need to set an x-axis variable.
Solution 2:[2]
Update: x-axis:
library(dplyr)
library(tibble)
my_matrix <- df %>%
column_to_rownames("cell_type") %>%
rename(Cells = Percentage) %>%
as.matrix()
my_Matrix <- apply(my_matrix, 2, cumsum)
my_Matrix <- my_Matrix - my_matrix / 2
par(mfrow = c(1, 3))
x <- barplot(my_matrix,
ylab = "Percentage",
col=c("red2", "green3", "slateblue4"),
border="white",
legend.text = rownames(my_matrix),
args.legend=list(cex=1,x = "topright"))
text(rep(x, each = nrow(my_Matrix)), my_Matrix, cex = 1.5, col = "white", labels = paste0(Percentage, "%"))
First answer:
Here is a base R barplot: as an alternative approach:
library(dplyr)
library(tibble)
my_matrix <- df %>%
column_to_rownames("cell_type") %>%
as.matrix()
my_Matrix <- apply(my_matrix, 2, cumsum)
my_Matrix <- my_Matrix - my_matrix / 2
par(mfrow = c(1, 3))
x <- barplot(my_matrix,
col=c("red2", "green3", "slateblue4"),
border="white",
# col = 1 + 1:nrow(my_matrix),
width = 0.5,
legend.text = rownames(my_matrix),
args.legend=list(cex=1,x = "topright"))
text(rep(x, each = nrow(my_Matrix)), my_Matrix, cex = 1.5, col = "white", labels = paste0(Percentage, "%"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |



