gpt4 book ai didi

r - R 中的圆环图自定义问题

转载 作者:行者123 更新时间:2023-12-04 16:11:56 25 4
gpt4 key购买 nike

我有如下所示的数据:

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

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

关于r - R 中的圆环图自定义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49416958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com