有没有一种简单的方法来制作一个水平的单一堆叠条形图与R?

bmvo0sr5  于 2023-01-10  发布在  其他
关注(0)|答案(3)|浏览(105)

如果有人能帮我用R绘制一个堆叠条形图,我将不胜感激。下面是一个要绘制的数据的小示例:

cell_type   Percentage
CD20 B cells    15.00
CD4 T cells 25.00
Other cells 60.00

这是我使用的,但不能修改太多。

p1 <-  ggplot(Data, aes(x = "", y = percentage, fill = cell_type))

p1

p2 <-  p1 + geom_col()
p2

预先感谢你的帮助。

sbdsn5lh

sbdsn5lh1#

使用coord_flip使其水平,要调整条形图粗细,请指定width参数,并且可以使用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()

如果您有多个条形图,则需要设置一个x轴变量。

f4t66c6m

f4t66c6m2#

也许你想要这样的东西:

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

输出:

piv4azn7

piv4azn73#

**更新:**x轴:

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

第一个答案:

以下是基准R条形图:作为替代方法:

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

相关问题