我的資料是:
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。
uj5u.com熱心網友回復:
這可能符合您的目的:
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")
結果:

uj5u.com熱心網友回復:
您需要先將資料轉換為長格式(整潔格式)。然后,我們可以指定 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")
輸出

uj5u.com熱心網友回復:
這是一種替代方法,values_transform用于獲取數字型別,然后使用geom_colwithposition_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))

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438213.html
