简体   繁体   中英

Order columns in geom_bar in ggplot in R

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")

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM