Order legend entries in R

Is it possible to order the legend entries in R?

If I e.g. specify a pie chart like this:

      plot_ly(df, labels = Product, values = Patients, type = "pie",
              marker = list(colors = Color), textfont=list(color = "white")) %>%
        layout(legend = list(x = 1, y = 0.5))

The legend gets sorted by which Product has the highest number of Patients. I would like the legend to be sorted in alphabetical order by Product.

Is this possible?

You need to either reorder your factor or specify order using a list in scale_colour_fill i.e. scale_colour_fill(labels=c(“1”, “2”, “3”, “4”). Sort of hack-y, but easier and less riskier than altering your dataframe directly.

I am sorry but I didn’t find any thing looking like : scale_colour_fill, anywhere in the reference sheet. Could you explain a little bit more ?