簡體   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