costebk08
costebk08

Reputation: 1359

Donut chart customization issue in R

I have data that looks like the following:

library(dplyr)
library(plotly)
df<-data_frame(Color=c("Green","Green","Yellow","Yellow","Gray","Gray","Red","Red"))
# A tibble: 8 x 1
Color
<chr>
Green
Green
Yellow
Yellow
Gray
Gray
Red
Red

I am attempting to create a donut chart where the slices correspond to the colors in the Color column and contain percentages as well as raw counts of the number of times a given color appears. I have tried this:

df %>%
group_by(Color) %>%
summarize(count = n()) %>%
plot_ly(labels = ~Color, values = ~count,colors=c("Green","Yellow","Red","Gray")) %>%
add_pie(hole = 0.6) %>%
layout(title = "test chart",  showlegend = T,
     xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
     yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

And it has given me the chart below. What can I add to change the colors and also add the raw counts to the slices (i.e., 2 in this case for each slice)

Upvotes: 1

Views: 207

Answers (1)

missuse
missuse

Reputation: 19726

Here is the desired syntax:

library(plotly)
df %>%
  group_by(Color) %>%
  summarize(count = n()) %>%
  plot_ly(labels = ~Color,
          values = ~count,
          text = ~count,
          textinfo = 'label+text',
          marker = list(colors = c("Green","Yellow","Red","Gray"))) %>%
  add_pie(hole = 0.6) %>%
  layout(title = "test chart",  showlegend = T,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)) 

enter image description here

so marker = list(colors = changes to colors of the slices. text + `textinfo - defines the custom text

Experiment a bit

EDIT: responding to the comment.

Usually the order of plotting of categorical variables in plotly depends on the order of factor levels. However not in this case, where the order is determined by the order of the data frame supplied. To change the order one can use match.

df %>%
  group_by(Color) %>%
  summarize(count = n()) -> df

colors = c("Green","Yellow","Red","Gray")



plot_ly(df[match(colors, df$Color),],
          labels = ~Color,
          values = ~count,
          text = ~count,
          marker = list(colors = colors)) %>%
  add_pie(hole = 0.6) %>%
  layout(title = "test chart",  showlegend = T,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)) 

enter image description here

Upvotes: 1

Related Questions