Search code examples
rggplot2ggplotly

Can't change the legend position in R


I am generating this chart using this code in R.

ggplotly(
 gplot(data=ComercioLineChart,aes(x=ComercioLineChart$Ano,y=ComercioLineChart$`Quantidade (L)`,color=ComercioLineChart$Categoria)) +
    geom_line(alpha = .5) + 
    geom_point(alpha = .5) +
    labs(title = "Comércio de categorias de vinhos por ano",subtitle = "1970-2016",caption = "Dados obtidos em: http://vitibrasil.cnpuv.embrapa.br/index.php?opcao=opt_01", y = "Quantidade (em milhões de litros)", x = NULL, color = "Categorias") +
    scale_y_continuous(n.breaks=10, labels = unit_format(unit = "M", scale = 1e-6)) +
    theme_bw() +
    theme(legend.position ="bottom")
    )

The problem is that I simply cannot change the legend position. I've tried with numbers, "top", "bottom" etc etc etc. Nothing works.

What am I doing wrong?

I wanted the legend to be smalled and get bellow the chart, so the chart would be wider

enter image description here


Solution

  • plotly has native functions to position the legend:

    p <- ggplotly(...)
    p %>% layout(legend = list(orientation = 'h', x = 0.5, xanchor = 'center', y = -0.3))
    

    example graph