[英]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。
這是使用values_transform
獲取數字類型然后使用geom_col
與position_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:
顯示值的示例代碼:
(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.