[英]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.