Home > front end >  Is there an easy way to make an horizontal single stacked Barplot with R?
Is there an easy way to make an horizontal single stacked Barplot with R?

Time:05-21

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.

CodePudding user response:

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.

enter image description here

CodePudding user response:

Maybe you want something like this:

library(tidyverse)
df %>%
  mutate(dummy = "v") %>%
  ggplot(aes(x = dummy, y = Percentage, fill = cell_type))  
  geom_col()  
  geom_text(aes(label = paste0(Percentage, "%")),
            position = position_stack(vjust = 0.5))  
  theme_minimal()  
  labs(x = "", y = "Percentage")

Output:

enter image description here

CodePudding user response:

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, "%"))

enter image description here

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, "%"))


enter image description here

  • Related