Ordering the bars of a bar graph in ggplot smallest to largest

Is there a way to indicate that I want the columns of the grouped histogram to be ordered using ggplot in terms of the sum of the four factors from smallest to largest? (so in the code below, I want to sort by the sum of all the variables) I have a sum for each x value in the data frame that I merged to create the data frame from which I formed the graph.

The code I use to plot the graph:

ggplot(md, aes(x=factor(fullname), fill=factor(variable))) + geom_bar() 

My current chart looks like this:

http://i.minus.com/i5lvxGAH0hZxE.png

As a result, I want to get a graph that looks something like this:

http://i.minus.com/kXpqozXuV0x6m.jpg

My data looks like this:

data in chart
(source: minus.com )

and I melt it into this form, where each student has a meaning for each category:

molten data http://i.minus.com/i1rf5HSfcpzri.png

before using the following line to plot

  ggplot(data=md, aes(x=fullname, y=value, fill=variable), ordered=TRUE) + geom_bar()+ opts(axis.text.x=theme_text(angle=90)) 

Now I'm not quite sure that I understand how Chi performs ordering, and whether I can apply this to data from any of my frames. It may be useful to have the data sorted in the original data frame that I have, the one that I show first.

UPDATE: We figured it out. See this thread for an answer: Order a histogram with accumulation in ggplot

+4
source share
1 answer

I'm not sure how your data was generated (i.e. do you use the cast / melt combination from the reshape package, which I suspect given the default name of your variables), but here is an example of toys where sorting is done outside of the call ggplot . There might be a much better way to do this, take a look at SO as suggested by @Andy.

 v1 <- sample(c("I","S","D","C"), 200, rep=T) v2 <- sample(LETTERS[1:24], 200, rep=T) my.df <- data.frame(v1, v2) idx <- order(apply(table(v1, v2), 2, sum)) library(ggplot2) ggplot(my.df, aes(x=factor(v2, levels=LETTERS[1:24][idx], ordered=TRUE), fill=v1)) + geom_bar() + opts(axis.text.x=theme_text(angle=90)) + labs(x="fullname") 

To sort in the opposite direction, add decr=TRUE with the order command. Additionally, as suggested by @Andy, you can overcome the problem of overlapping x-tags by adding + coord_flip() instead of the opts() parameter.

enter image description here

+6
source

Source: https://habr.com/ru/post/1380809/


All Articles