Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Plotly pie chart custom colors

I have been struggling with this issue for days if someone can help me with. I have a table data which has a column 'results' with values "High", "Medium" or "low". I am trying to create a pie chart using plotly by counting the number of High, Medium and Low in the data set and trying to assign a color to each category. Below is my code. I have tried cols1 and cols2 as my marker and several other ways but nothing seems to work. Please keep in mind that this is a dynamic table so there might be cases when there is no High or no Medium etc. so I just cannot use list(c("tomato","ornage","olivedrab") as the marker. Color has to be tied to the result category.

 tab <- count(data, results)

  tab <- transform(tab,
                   results_ord  = factor(
                     results ,
                     levels = c('High', 'Medium', 'Low'),
                     ordered = TRUE
                   ))
  cols1 <-
    c(
      High = "olivedrab",
      Medium = "orange",
      Low = "tomato"
    )
  cols2 <-
    c(ifelse(
      tab$results_ord == "High",
      "olivedrab",
      ifelse(
        tab$results_ord == "Medium",
        "orange",
        "tomato"
      )
    ))


  plot_ly(
    tab,
    labels = results_ord,
    values = n,
    marker = list(cols2),
    type = "pie"
  ) %>%
    layout(title = "Results")

  thanks,

Manoj Agrawal

like image 840
Manoj Agrawal Avatar asked Oct 12 '16 16:10

Manoj Agrawal


1 Answers

This syntax is for 4.x version of plotly, but you can adjust accordingly for older verison. Here is how you can get manual colors to show up:

df <- count(mtcars, am)
plot_ly(df, values = ~n, labels = ~factor(am), marker = list(colors = c('#FF7F0E', '#1F77B4')), type = 'pie')

You can adjust factor orders to get desired color for the desired value.

like image 68
Gopala Avatar answered Nov 09 '22 23:11

Gopala