我的数据如下所示:
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))
答案 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))
所以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))