【问题标题】:ggplot2 geom_bar: plot sum of two variables and group by proportion of each variableggplot2 geom_bar:绘制两个变量的总和并按每个变量的比例分组
【发布时间】:2019-05-03 12:26:57
【问题描述】:

我找不到以下问题的答案/解决方案:

我有两个数值变量。我取两者的总和,并希望绘制该总和变量的相对频率 + 表示其子分量的比例(即一个变量的平均比例作为总和的一部分)。

示例:我有 v1 = 问题数和 v2 = 答案数。每个观察可以有 x 个问题和 y 个答案以及 x+y 个交互。

示例代码:

df <- data.frame(matrix(ncol = 2, nrow = 5))
x <- c("questions", "answers")
colnames(df) <- x

df$questions <- c(1,2,3,1,2)
df$answers <- c(2,3,4,2,3)
df$interactionsum <- df$questions + df$answers


ggplot(df, aes(x = interactionsum)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) + 
  ylab("Relative frequencies") +
  xlab("Sum of interactions")

在此数据设置中,第一个条的三分之一是问题(平均比例),三分之二是答案(平均比例)。如何使用 ggplot2 实现这种类型的分组?

提前谢谢你!

【问题讨论】:

  • 但是每个变量的比例可以在一个总和内变化。你想要平均比例吗?
  • 是的,我知道,是的! :-) 最好是为每个平均比例设置一个误差线,但没有必要
  • 您想如何在条形图中绘制 x 轴上的交互总和和 y 轴上的相对频率?
  • 您提到了“第一个小节的三分之一”。你预计有多少酒吧?如果你想要“平均比例”,它应该只有一个栏。
  • @franziskalypse 他将总和视为一个因素。

标签: r ggplot2


【解决方案1】:
df <- data.frame(matrix(ncol = 2, nrow = 5))
x <- c("questions", "answers")
colnames(df) <- x

df$questions <- c(1,2,3,1,2)
df$answers <- c(2,3,4,2,3)
df$interactionsum <- df$questions + df$answers

require(dplyr) 
require(tidyr)
require(ggplot2) 
df<-df  %>% group_by(interactionsum) %>% 
  summarize(questions=mean(questions)/mean(interactionsum) ,answers=mean(answers)/mean(interactionsum) , n=n()/nrow(df) ) %>% mutate(interactionsum=as.factor(interactionsum)) %>% 
  gather("key","means",questions, answers) 
ggplot(df,aes(x=interactionsum,y=means*n,fill=key))+geom_bar(stat="identity")

对于每个可能的交互和,我们创建所有问题变量的平均值和所有答案变量的平均值。然后我们收集(使用tidyr)以制作 ggplot 偏爱的长数据格式,然后我们使用“身份”统计将这些均值绘制在堆积条形图中,因为它们已经反映了值中的频率。

我还将交互总和转化为一个因素,以改善最终结果的外观。

【讨论】:

  • 现在显示的是相对频率而不是病例数。
【解决方案2】:
# example data
df = data.frame(questions = c(1,2,3,1,2),
                answers = c(2,3,4,2,3))

df$interactionsum <- df$questions + df$answers

library(tidyverse)

df %>%
  group_by(interactionsum) %>%
  summarise_all(sum) %>%
  gather(x,y,-interactionsum) %>%
  group_by(interactionsum) %>%
  mutate(y = y/sum(y)) %>%
  ggplot(aes(interactionsum, y, fill=x))+
  geom_bar(stat="identity")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2023-02-23
    • 2017-01-11
    • 2013-08-31
    • 1970-01-01
    相关资源
    最近更新 更多