0
votes

I've a data frame (mmt.ranking.sum_2) with a list of 25 questions (1st column 'questions').

The question-strings are consecutively preceded by 9a-h, 10a-j, 11a-g; i.e. numbered

For each question there are counts of answers in classes from r0-r5 (2.-7. column)

questions              r0 r1 r2 r3 r4 r5
9a 'question text'     1 1 0 8 3 8
9b 'question text'     1 0 2 7 7 4
...
9h 'question text'     1 6 4 7 3 0
10a 'question text'    ...
...
10j 'question text'    ...
...

11g 'question text'    ...

This is melted & values are drawn into a stacked bar chart

df.melt<-melt(mmt.ranking.sum_2[,1:7], id.vars="questions")

ggplot(df.melt, aes(questions, value, fill=variable)) + geom_bar()+ coord_flip() + theme_bw()+ scale_fill_brewer()

In the original data frame (see above) & in the melted one

questions variable value

9a'question text' r0 1

9b'question text' r0 1

...

9a'question text' r1 2

...

11g'question text' r5 2

the order of the questions is correct: 9a-h, 10a-j, 11a-g

But the order changes & reverses strangely in the final chart ('coord_flip' causes horizontal bars).

top > down: 9h-9a, 11g- 11a, 10j-10a

Any ideas why and how I can keep the original order?

Any help appreciated

Thanks, Georg

1
Please do some effort to format your question. I tried to clean it but without success. We should just copy and paste your code in order to help to find a solution.agstudy

1 Answers

0
votes

You should reorder your x axis using reorder, Try this for example , Replace

aes(questions,..)

by

aes(reorder(questions,as.numeric(gsub('([0-9]+).*','\\1', 
             df.melt$questions)),...)

You don't give a reproducible example So I can't be sure from the given solution. Here some code to generate your questionnaire data ( I spent 30 minutes to generate your data and less than one minute to find a solution, so please try to reproduce data next time).

## 6 questions
N <- 6  
set.seed(123)
let <- sample(1:5,N,rep=TRUE)
qs <- lapply(seq(N),
       function(x){
         nn <- paste0(x,letters[1:20][seq(let[x])])
         somtext <- replicate(3,paste(sample(c(0:9, letters, LETTERS),
                      5, replace=TRUE),
               collapse=""))
         paste(nn,'question text',paste0(somtext,collapse=' '))

       })

questions <- unlist(qs)

dat <- matrix(sample(0:8,length(questions)*6,rep=TRUE),ncol=6)

colnames(dat) <- paste0('r',0:5)
dat <- data.frame(questions,dat)

library(reshape2)
df.melt <- melt(dat, id.vars="questions")

Then when I plot it using :

ggplot(df.melt, aes(reorder(questions,as.numeric(gsub('([0-9]+).*','\\1', df.melt$questions)))
                    ,value, fill=variable)) +
  geom_bar(stat='identity')+ 
  theme_bw()+ 
  coord_flip() +
  scale_fill_brewer()

`enter image description here