0

I tried to finde a solution for my problem but I could not. Probably, my problem is easy for some of you. However, I need support. I would be greatful for any help.

I have made a ggplot for two factors: HGU_type and cycle_complexity to show their proportions:

I used:

g2<-ggplot(t,aes(x=HGU_type,fill = cycle_complexity))+ geom_bar(position="fill") 
g2

The graph, I get looks as follow:

I want to have increasing order of the bars on the x-axis...first bar with "nod", second with "shake", third with "retr"...

I tried everything and cannot find the solution.

I would be grateful for a hint

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Jo-Achna
  • 315
  • 1
  • 3
  • 14
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to produce a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). This will make it much easier for others to help you. – Jaap Jul 12 '14 at 14:19

1 Answers1

2

As @Japp pointed out, it's always best to include a minimal reproducible example with your question. I created this data set

#sample data
set.seed(18)
t<-data.frame(
    HGU_type=sample(c("jerk","nod","pro","retr","shake","tilt","turn"), 50, replace=T, prob=sample(7)),
    cycle_complexity=sample(c("multiple", "single"), 50, replace=T)
)

And a plot like your original one is created by

ggplot(t,aes(x=HGU_type,fill = cycle_complexity))+ geom_bar(position="fill")

enter image description here

In order to change the order in which the bars are drawn, you need to change the levels of the factor used for the x-axis. The reorder() function makes it easy to reorder factors based on different properties. Here we will re-order based on the proportion of "multiple" in each group

t$HGU2<-reorder(t$HGU_type, t$cycle_complexity,FUN=function(x) mean(as.numeric(x)))

Then we can plot with

ggplot(t,aes(x=HGU2,fill = cycle_complexity))+ geom_bar(position="fill")

to get

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • I am new here and was not sure how does asking questions work in stacoverflow. Nevertheless, thank you so much for your answers. You made my day! – Jo-Achna Jul 12 '14 at 19:14