繁体   English   中英

具有频率计数的堆叠条形图 ggplot2

[英]Stacked Barplot with Frequency Counts ggplot2

我有一个包含多个条件的数据集,我想创建一个堆叠条形图,显示每个条件下发生的错误频率。 (因此,在每种情况下发生 1 个错误、发生 2 个错误、发生 3 个错误的情况数……等等)

理论上,我理解了用ggplot2创建条形图的原理。 但是,我遇到的问题是“频率”计数不是数据框中的实际变量(因为它需要计算案例数)。 我不确定如何将它添加到 gpplot2 框架中(可能使用 'stat' 函数,但我不太确定它是如何工作的)。

我检查了以下类似的问题:

如何使用 ggplot2 绘制频率条形图?

R 堆积百分比频率直方图与基于聚合数据的百分比

在ggplot中使用geom_bar()显示频率而不是计数

如何在ggplot中标记堆叠直方图

但是它们都没有真正提供我正在寻找的答案(即,如何计算每个“错误”的案例数量并将其包含在 ggplot2 代码中。

以下是我对示例数据的一些尝试

library(tidyverse)

condition <- c("condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3")
number_of_errors <- c(1,2,3,3,2,1,4,4,5,4,5,1,2,2,3)

df <- data.frame(condition, number_of_errors)
df

df_melt <-melt(df) #This creates a data frame with 3 columns, 'condition', 'variable' and 'value' where 'variable' just says 'number_of_errors' for each row


# Attempt 1 - (Error: stat_bin() can only have an x or y aesthetic.)
ggplot(df_melt, aes(x=condition, y = variable, fill=value)) + 
  geom_bar(stat="bin", position="stack") +
  xlab("Condition") + 
  ylab("Frequency of Errors")


# Attempt 2 (produces a graph, but not a stacked one, just the total number of cases in each condition)
ggplot(df_melt, aes(x = condition, fill = value, label = value)) +
  geom_bar(col="black") +
  stat_count(position="stack")


# Attempt 3 (also produces a graph, but again not a stacked one - I think it is the sum of the number of errors?)
ggplot(df_melt,aes(factor(condition),y=as.numeric(value))) + 
  geom_bar(stat = "identity", position = "stack")

我确定我一定遗漏了一些关于如何为计数创建值的明显内容,但我不确定是什么。 任何指导表示赞赏:)

也许您正在寻找这种情节风格。 您需要按条件分组,然后分配一个值,以便可以设计条形。 这里的代码:

library(tidyverse)
#Data
condition <- c("condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3", "condition 1", "condition 2", "condition 3")
number_of_errors <- c(1,2,3,3,2,1,4,4,5,4,5,1,2,2,3)
df <- data.frame(condition, number_of_errors)
#Code
df %>% group_by(condition) %>% mutate(Number=factor(1:n())) %>%
  ggplot(aes(x=condition,y=number_of_errors,fill=Number,group=Number))+
  geom_bar(stat = 'identity')+
  geom_text(aes(label=number_of_errors),position = position_stack(0.5))+
  theme(legend.position = 'none')

输出:

在此处输入图片说明

我认为您的关键可能是将number_of_errors转换为一个因子并使geom_bar(stat="count")您也可以从本教程中受益

library(ggplot2)
df$number_of_errors <- factor(df$number_of_errors)

ggplot(df, aes(x=condition, fill = number_of_errors)) +
  geom_bar(stat="count")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM