% g-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:32:05 28 4
gpt4 key购买 nike

我的数据是:



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。

最佳答案

这可能符合您的目的:

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

结果: enter image description here

关于r - 如何使用 ggplot 在 r 中创建堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71359655/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com