0

I have a time-series data frame:

Data frame

The column "Contas.Resultado" is ordered correctly by ascending order of "Valor" column.

My problem is:

When I plot the chart, the legend doesn't appear in the correct order, consequently, some geom_area plot overlap others.

ggplotly(tbl1 %>% ggplot(aes(Ano, Valor)) + 
  geom_area(aes(fill = Contas.Resultado), 
            position = position_dodge(width = 0), stat = "identity") +    
  scale_x_yearmon() +
  xlab("") +
  ylab("R$ (milhões)")) 

Overlap Chart

I got the right results using this:

df$Contas.Resultado <- factor((df$Contas.Resultado), 
                              levels = c("Faturamento", "Receita Líquida", 
                                         "Resultado Bruto", "EBTIDA R$", "EBTI",
                                         "Resultado Líquido"))

I would appreciate if someone knows a straightforward way to solve this

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Gui_99
  • 51
  • 7
  • 2
    I often define my fill variable as a factor to have it be ordered correctly. – Ryan Morton Apr 05 '18 at 16:28
  • @RyanMorton is exactly right. You need to change the `fill` variable to a factor and include ordering in the `as.factor()` statement before plotting. – Steven Apr 05 '18 at 16:50
  • I have used `df <- factor((df$Contas.Resultado), ordered=TRUE)`, but It doesn't work. Same result. – Gui_99 Apr 05 '18 at 16:56
  • Can you please `dput` and share your data.frame? – MKR Apr 05 '18 at 17:55
  • [Dataframe](https://ufile.io/zj7cn) – Gui_99 Apr 05 '18 at 18:16
  • @Gui_99 please do not share your data via link to an external site. Not everyone would be willing to download files onto their own laptops. Your file doesn't appear to be that huge. As MKR commented, `dput()` is preferred. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Z.Lin Apr 07 '18 at 09:04

1 Answers1

0

Try using the forcats package from Hadley Wickam's tidyverse. You should be able to order the months as levels. Possible solution from Hadley's site:

month_levels <- c(
  "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
)

factor(x1, month_levels)


#> [1] Dec Apr Jan Mar
#> Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

Does this work for you?

wissem
  • 58
  • 8
  • Yes, it worked fine. Is there a way to do that, without having to naming manually ? – Gui_99 Apr 05 '18 at 20:10
  • Not that I'm familiar with. There must be, but I haven't been able to find a more automated solution yet. Maybe there isn't an (easily) automated version because usually, it isn't necessarily obvious what order a variable should be in (if you want to organize by number of days in the month, or coldest month, for example). – wissem Apr 06 '18 at 20:57
  • You could potentially extract a list using summarize from dplyr, and then use that for your levels but not as helpful for this specific example. – wissem Apr 06 '18 at 20:58