R中的圆环图自定义问题

时间:2018-03-21 21:39:39

标签: r data-visualization pie-chart donut-chart

我的数据如下所示:

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)

1 个答案:

答案 0 :(得分:1)

这是所需的语法:

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

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

enter image description here