使用ggplot和一个Likert量表的矩阵在R中堆积条形图

时间:2022-02-15 14:58:09

this is my first question here. I've searched for an answer before, but I wasn't able to find a satisfying one - probably because I am an absolute beginner with R.

这是我的第一个问题。之前我曾经找过一个答案,但我找不到令人满意的答案 - 可能是因为我是R的绝对初学者

I have the following data:

我有以下数据:

      pbw1 pbw2 pbw3 pbw4 pbw5 pbw6
[1,]   2   3   2   1   0   2    3
[2,]   2   1   1   3   4   5    6

PBW is a variable answered on a likert scale. This dataset has 1014 rows, so this is just an example.

PBW是以Likert量表回答的变量。此数据集有1014行,因此这只是一个示例。

What I need is a figure that looks like that:

我需要的是一个看起来像这样的图:

使用ggplot和一个Likert量表的矩阵在R中堆积条形图

For my dataset this means: 6 items (I'd like to replace pbw with a sentence in the end) on the x-axis and therefore 6 bars. These should show how many persons of the n=1014 (in percent) have answered the item. Like, 80% have answered with 0, 10% answered with 1, 5% answered with 5%, etc. This should obviously be cumulative.

对于我的数据集,这意味着:在x轴上有6个项目(我想用最后的句子替换pbw),因此有6个条形。这些应该显示n = 1014(百分比)中有多少人回答了该项目。比如,80%的人回答0,10%回答1%,5%回答5%等等。这显然应该是累积的。

All I read is ggplot, melt, and so on. Yet I am just unable to get R to do what I want and need.

我读的只是ggplot,融化等等。然而,我无法让R去做我想要和需要的事情。

This didn't help:

这没有帮助:

datm = melt(cbind(pbwmatrix, ind=rownames(pbwmatrix)), id.vars=c('ind'))

datm = melt(cbind(pbwmatrix,ind = rownames(pbwmatrix)),id.vars = c('ind'))

Also barplot(pbwmatrix) did not; also several silly combinations of random commands did not (yes, I am desperate).

barplot(pbwmatrix)也没有;也有几个愚蠢的随机命令组合没有(是的,我很绝望)。

Help in any way would be much appreciated!

任何方式的帮助将不胜感激!

1 个解决方案

#1


2  

Here's a starter using ggplot:

这是使用ggplot的启动器:

df <- as.data.frame(replicate(6, sample(1:6,100,T)))
library(tidyverse)
df %>% 
  gather %>% 
  group_by(key, value) %>% 
  tally %>% 
  mutate(n = n/sum(n)*100) %>% 
  ggplot(aes(x=key, y=n, fill=as.factor(value))) + 
  geom_col() + 
  geom_text(aes(label=n), position=position_stack(.5)) + 
  coord_flip()

#1


2  

Here's a starter using ggplot:

这是使用ggplot的启动器:

df <- as.data.frame(replicate(6, sample(1:6,100,T)))
library(tidyverse)
df %>% 
  gather %>% 
  group_by(key, value) %>% 
  tally %>% 
  mutate(n = n/sum(n)*100) %>% 
  ggplot(aes(x=key, y=n, fill=as.factor(value))) + 
  geom_col() + 
  geom_text(aes(label=n), position=position_stack(.5)) + 
  coord_flip()