繁体   English   中英

如何使用 ggplot 在 r 中创建堆积条形图

[英]How to create a stacked bar chart in r with ggplot

我的数据是:



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。

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

library(tidyverse)

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

Output

在此处输入图像描述

这可能符合您的目的:

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

结果: 在此处输入图像描述

这是使用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))

在此处输入图像描述

另一种解决方案ios 并列的使用吧。

样本数据:

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

Plot: 在此处输入图像描述

Plot:

显示值的示例代码:

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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM