-1

I'm trying to order my ggplot columns on a descending order but the code isn't working properly.

Here's the code:

Consolidado_novo %>%
 ggplot(aes(reorder(categoria, pesquisa_mensal), pesquisa_mensal)) + 
 geom_col(aes(x=categoria, y=pesquisa_mensal), fill="orange") + 
 labs(x = "Categorias",
   y = "Volume Mensal Pesquisas",
   title = "Análise KW Cosméticos")

Tha graph:Graph

The dataset:

Keywords categoria Currency pesquisa_mensal mudanca_3meses
1 oxibenzona protetor solar Protetor Solar BRL 90 -57%
2 protetor solar com oxibenzona Protetor Solar BRL 30 25%
3 quais protetores solares tem oxibenzona Protetor Solar BRL 20 100%
4 avobenzona protetor solar Protetor Solar BRL 20 -67%
5 protetor solar sem oxibenzona Protetor Solar BRL 110 0%

Any hints?

  • Welcome - try to be more specific than 'code isn't working properly' - what exactly isn't working properly? Thank you. – user438383 Nov 29 '21 at 15:44
  • 5
    I think every question on SO and elsewhere that references ggplot2 and "order of" something is resolved with the use of `factor(.., levels=..)`. – r2evans Nov 29 '21 at 15:45
  • 2
    But this question doesn't appear to be reproducible, as the sample data and code produce (for me) a single column of `Protetor Solar`. It helps immensely if the sample data actually demonstrates the variability you intend. Can you update your data to include at least one more `categoria`, and where the default order is counter to what you intend? – r2evans Nov 29 '21 at 15:47
  • My best guess is that you shouldn't specify `x =` two times in different ways. Keep the one with `reorder`, delete `x=categoria`. – Gregor Thomas Nov 29 '21 at 15:57
  • Does this answer your question? [Order discrete x scale by frequency/value](https://stackoverflow.com/questions/3253641/order-discrete-x-scale-by-frequency-value) – camille Nov 29 '21 at 20:29

1 Answers1

0

See forcats::fct_reorder.

The example provided is not reproducible, but this should do the trick:

df <- data.frame(categoria = LETTERS[1:5],
                 pesquisa_mensal = c(20,100,110,90,50))

library(tidyverse)
df %>%
    mutate(categoria = fct_reorder(categoria, pesquisa_mensal, .desc = TRUE)) %>%
    ggplot(aes(categoria, pesquisa_mensal)) +
    geom_col()

Created on 2021-11-29 by the reprex package (v2.0.1)

csgroen
  • 2,511
  • 11
  • 28