1

I wish I could sort the values for each facet in descending order.

I used reorder (Agent, -value) but it doesn't work.

A part of my data :

Country        Agent        Period  Level    Location   variable    value
361 e   L    2016_2017  1   d   11  8
362 e   S    2016_2017  1   d   11  1
363 e   C    2016_2017  1   d   11  12
364 e   B    2016_2017  1   d   11  6
365 e   A    2016_2017  1   d   11  5
366 e   D    2016_2017  1   d   11  2

My simplified code :

library(ggplot2)
# toy data
data = data.frame(Country = c("e","e","e","e","e","e","e","e","e","e","e","e"),
                  Agent = c("L","S","C","B","A","D","L","S","C","B","A","D"),
                  Period = c("2016_2017","2016_2017","2014_2015","2014_2015","2011_2012","2011_2012","2016_2017","2016_2017","2014_2015","2014_2015","2011_2012","2011_2012"),
                  Level = c("1","1","1","1","1","1","1","1","1","1","1","1"),
                  Location = c("d","d","d","d","d","d","d","d","d","d","d","d"),
                  variable = c("11","11","11","11","11","11","21","21","21","21","21","21"),
                  value = c(8,1,12,6,5,2,4,6,1,0,6,3))

# most importants parts of my plot, related to the question
ggplot(data, aes(x = reorder (Agent, -value), y = value)) +
  geom_bar(position = "dodge", stat = 'identity') +
  facet_grid(Period~variable, scales = "free", space="free")

Here is the ouput of my full code:

enter image description here

Paul
  • 2,850
  • 1
  • 12
  • 37
cdjemiel
  • 33
  • 6
  • Hello and welcome to StackOverflow! In order for us to help you, please provide a [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) example. For example, to produce a minimal data set, you can use `head()`, `subset()`. Then use `dput()` to give us something that can be put in R immediately. Alternatively, you can use base R datasets such as `mtcars`, `iris`, *etc*. – Paul Aug 19 '20 at 09:21
  • @Paul Hi, yes sorry i put my table (head(data)) and my plot :) – cdjemiel Aug 19 '20 at 10:27
  • 1
    in `facet_grid` the X axis is in common between graphs, therefore having the bars in orders for each chart is technically impossible. (unless the order is ALWAYS the same). X axes need to be independent for that to happen with no mistakes. You need to create a new variable for X that takes care of the order of values. – Edo Aug 19 '20 at 10:48
  • 1
    @cdjemiel I can see your data (probably the output of `head(data)`) but it is still not possible to make the object `data` with your code. If you want to use your data, please consider doing something like `dput(data)` or `dput(head(data))` and copy/paste the result shown in the console in your question. – Paul Aug 19 '20 at 11:14
  • @Paul thks, i create a data variable with a part of my data (it is very simplified)! – cdjemiel Aug 19 '20 at 11:50
  • @Edo thanks, and how to do this ? because i must group by two variables (ie Period~variable) my values ? – cdjemiel Aug 19 '20 at 11:52
  • something like this probably. `data %>% group_by(Country, level, Location, Period, variable) %>% arrange(-value) %>% mutate(order = row_number()) %>% ungroup()` Can't be sure without a reproducible example. `order ` should be the variable to use on the X axis. – Edo Aug 19 '20 at 11:57
  • @cdjemiel thanks for the data :) Do you really need to have 1 plot with facets or is it ok to get many plots (1 per current facet)? – Paul Aug 19 '20 at 11:58
  • 1
    @Paul I would prefer to have 1 plot with facets but if it's easier let's go to many plots (1 per current facet). – cdjemiel Aug 19 '20 at 12:14
  • @cdjemiel I found [this](https://drsimonj.svbtle.com/ordering-categories-within-ggplot2-facets) tutorial, you might find interesting tips by reading carefully the part about data. Sry I can't do it now... – Paul Aug 19 '20 at 12:14
  • @Paul Ok, thks i will see this tuto ! – cdjemiel Aug 19 '20 at 12:22
  • @Edo, indeed it works perfectly but is it possible to plot my X axis labels (ie Agent label)? – cdjemiel Aug 19 '20 at 12:24
  • not in the right order, because the order will be unique for each bar plot. – Edo Aug 19 '20 at 13:04
  • unless you use `facet_wrap` or you create each barplot separatly and then you plot them together. – Edo Aug 19 '20 at 13:12
  • also I think that what you mean to use is `fill = Agent` which colours the bars inside – Edo Aug 19 '20 at 13:13

1 Answers1

0

You could try this approach. The function reorder_within() from tidytext package allows to reorder at deep levels as you will see in the aes() term of the plot. I have reused the code you posted and included the modification:

library(tidytext)
library(ggplot2)

#Plot
ggplot(subset(data, Country %in% c("e") & Level %in% c("1") & Location %in% c("d")),
       aes(x = reorder_within(Agent, -value, variable), y = value, colour = Agent)) +
  geom_bar(position = "dodge", stat = 'identity')+
  facet_grid(Period~variable, scales = "free", space="free") +
  theme_bw() +
  theme(plot.title = element_text(size = 14, face = "bold"),
        text = element_text(size = 12, family = ""),
        axis.title = element_text(face="bold"),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(), 
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        strip.text.x = element_text(size = 10, colour = "Black", angle = 0),
        strip.text.y = element_text(size = 10, colour = "Black", angle = 0),
        legend.position = "none")

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • thank you very much, this works with this simplified dataset but when i give my whole dataset it doesn't work (see https://imgur.com/a/PXYXjZT). – cdjemiel Aug 19 '20 at 14:47
  • @cdjemiel Could you please check if the variables used inside `reorder_within()` are factors or characters? – Duck Aug 19 '20 at 14:48
  • so Agent and variable are factors but value not (it is int) – cdjemiel Aug 19 '20 at 14:51
  • Could you please try changing the format? Use `df$Agent <- as.character(df$Agent)` and `df$variable <- as.character(df$variable)` with `df` being your dataframe for the plot. Include these code before the plot and re run again the plot. Let me know how that goes! – Duck Aug 19 '20 at 14:53
  • to load my tsv file i use stringsAsFactors=TRUE (because my colnames begin with int sometimes), so i must to transform Factor to characters maybe ? – cdjemiel Aug 19 '20 at 14:54
  • @cdjemiel Yes, better use `stringsAsFactors=F` in your loading to avoid transforming! Then re run the plot with the new loaded data! Let me know how that works! – Duck Aug 19 '20 at 14:57
  • @@Duck Nope, it doesn't work, I even tried to change the format of df$value to numeric instead of int – cdjemiel Aug 19 '20 at 15:03
  • @cdjemiel I see. How long is your data? Maybe you could open a chat here and I could help you with the issue. I believe is a matter of data types! – Duck Aug 19 '20 at 15:04
  • yes we can use the chat but it failed ... my data when i transform with `data.table::melt` do 21600 obs. – cdjemiel Aug 19 '20 at 15:38
  • @cdjemiel Check this: https://meta.stackexchange.com/questions/187426/how-do-i-chat-with-another-user-on-stackoverflow I suspect what is the issue and how to solve! – Duck Aug 19 '20 at 15:58