簡體   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