R 中的圆环图自定义问题

Donut chart customization issue in R

我的数据如下所示:

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

我正在尝试创建一个圆环图,其中切片对应于 Color 列中的颜色,并包含百分比以及给定颜色出现次数的原始计数。我试过这个:

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))

它给了我下面的图表。我可以添加什么来更改颜色并将原始计数添加到切片中(即,在这种情况下,每个切片 2 个)

这是所需的语法:

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)) 

所以 marker = list(colors = 改变切片的颜色。 text + `textinfo - 定义自定义文本

稍微试验一下

编辑:回复评论。

通常 plotly 中分类变量的绘制顺序取决于因子水平的顺序。但是在这种情况下不是,顺序由提供的数据帧的顺序决定。要更改顺序,可以使用 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))