如何使用 ggplot 在 R 中创建堆叠条形图

3

我的数据是:



positive <- c("21", "22", "33", "21", "27") ##Percentage
negative<- c("71", "77", "67", "79", "73")  ##Precentage 
sample <- c("Hr", "Fi", "We", "Pa", "Ki")
mydata <- data.frame(positive , negative, sample)

我想创建一个堆积条形图展示每个类别在样本变量中的正负百分比。我尝试了以下代码:

ggplot(mydata) +
  geom_bar(aes(x = sample, fill = positive))

但是并没有起作用。 如果这个问题看起来很基础,请原谅,我几周前才开始接触R语言。


这个回答解决了你的问题吗?堆叠条形图 - zephryl
你应该更具体地说明,特别是哪些部分没有起作用,同时也要说明你想要的效果。你的代码只会显示每个样本的行数计数 - 这是你想要的吗? - camille
4个回答

1

首先需要将数据转换为长格式(整洁格式)。然后,我们可以指定x轴(sample)、y轴(value)和填充(name)条件。

library(tidyverse)

mydata %>%
  pivot_longer(-sample) %>%
  ggplot(aes(fill = name, y = value, x = sample)) +
  geom_bar(position = "stack", stat = "identity")

输出

输入图像描述


1
这可能符合您的需求:
library(tidyverse)
mydata %>% pivot_longer(cols = !sample, names_to = "status", values_to = "percentage") %>% 
 ggplot(aes(fill = status, x = sample, y = percentage)) + 
 geom_bar(position = "stack", stat = "identity")

结果: 图片描述

1

这里提供一种替代方法,使用values_transform来获取数字类型,然后使用geom_colposition_fill和百分比功能:

library(dplyr)
library(tidyr)
library(ggplot)
library(scales)

mydata %>% 
  pivot_longer(
    cols = -sample,
    names_to = "status",
    values_to = "percentage", 
    values_transform = list(percentage = as.integer)
  ) %>% 
  ggplot(aes(x = sample, y=percentage, fill=status))+
  geom_col(position = position_fill()) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = percentage),
            position = position_fill(vjust = .5))

enter image description here


1

另一个解决方案是使用并排的条形图。

样例数据:

values <- c(21, 22, 33, 21, 27, -71, -77, -67, -79, -73) ##Percentage
sample <- factor(c("Hr", "Fi", "We", "Pa", "Ki"))
mydata <- data.frame(values, sample)

示例代码:

(ggplot(mydata, aes(x = sample, y = values)) +
  geom_bar(
    stat = "identity", position = position_stack(),
    color = "white", fill = "lightblue") +
  coord_flip())+
  labs(x="Sample",y="Percentage")+
  theme_bw()

情节:enter image description here

样例代码以显示值:

(ggplot(mydata, aes(x = sample, y = values)) +
  geom_bar(
    stat = "identity", position = position_stack(),
    color = "white", fill = "lightblue"
  ) +
    geom_text(aes(label = values))+
  coord_flip())+
  labs(x="Sample",y="Percentage")+
  theme_bw()

在此输入图片描述

如果您希望用不同的颜色标记正负条

(ggplot(mydata, aes(x = sample, y = values)) +
  geom_bar(
    stat = "identity", position = position_stack(),
    fill= ifelse(mydata$values < 0,"#ffcccb","lightblue")
  ) +
    geom_text(aes(label = values))+
  coord_flip())+
  labs(x="Sample",y="Percentage")+
  theme_bw()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接