Reputation: 1
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.
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.
What I need is a figure that looks like that:
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.
All I read is ggplot, melt, and so on. Yet I am just unable to get R to do what I want and need.
This didn't help:
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).
Help in any way would be much appreciated!
Upvotes: 0
Views: 1195
Reputation: 54287
Here's a starter using 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()
Upvotes: 2