使用 R 在绘图中选择前 3 个父母(组) [英] Select top 3 parents (groups) in plotly graph using R
问题描述
我想要的是仅绘制我的 父母
中的 3 个,其中 cost
花费最高的那些.
What I want is to plot only 3 of my parents
, the ones that spend the highest cost
with below coding.
parent <- as.character(c("Sam","Elena","Sam","Jhon","Raul","Sam","Jhon","Sara","Paul","Chris"))
cost <- as.numeric(as.character(c(15000,10000,12000,15000,10000,12000,15000,14000,19000,2000)))
topic <- as.character(c("Banana","Banana","Berries","Apple","Watermelon","Banana","Berries","Avocado","Watermelon","Pinneaple"))
sample <- as.data.frame(cbind(parent,cost,topic))
sample$cost <- as.numeric(as.character(sample$cost))
sample$parent <- as.character(sample$parent)
sample$topic <- as.character(sample$topic)
# Color setting
ramp2 <- colorRamp(c("deepskyblue4", "white"))
ramp.list2 <- rgb( ramp2(seq(0, 1, length = 15)), max = 255)
plot_ly(sample, x = ~parent, y = ~cost, type = 'bar', color = ~topic) %>%
layout(yaxis = list(title = 'Cost'), xaxis = list(title = 'Parent'), barmode = 'stack', colorway = ramp.list2) %>%
config(displayModeBar = FALSE)
我尝试在 plotly
函数中使用 transforms
,如下所示:
I tried to use transforms
inside plotly
function, like this:
transforms = list(
list(
type = 'aggregate',
groups = sample$parent,
aggregations = list(
list(
target = 'x',
func = 'max',
enabled = T))
))
但它仍然给我相同的输出,我只想选择 3.另外,尝试像这样使用它:
But it still gives me the same output and I want to select only 3. Also, tried to use it like this:
transforms = list(
list(
type = 'filter',
target = 'y',
operation = '>',
value = cost[-3:-1]))
但它只需要花费而无需花费全部 cost
parent
并且只给我 2 个父母而不是 3 个.最后,它没有使用 ramp.list2
选择颜色.
But it takes only cost without takin the full cost
parent
spent on and only gives me 2 parents instead of 3. And finally, it's not using ramp.list2
to select colors.
推荐答案
根据我的理解,可以用下面的代码分别获取前3个父级,如下:
According to what I understood, you can use the following code to get the top 3 parents separately, as follows:
top_3 <- sample %>%
group_by(parent) %>%
summarise(cost = sum(cost)) %>%
arrange(-cost) %>%
head(3)
这将为您提供以下信息:
This will give you the following:
# A tibble: 3 x 2
# parent cost
# <chr> <dbl>
# 1 Sam 39000
# 2 Jhon 30000
# 3 Paul 19000
然后,在你的plot_ly
中,你可以直接引用这些top_3的parent,如下:
Then, in your plot_ly
, you can just refer to these top_3 parents, as follows:
plot_ly(sample[sample$parent %in% top_3$parent,], x = ~parent, y = ~cost, type = 'bar', color = ~topic) %>%
layout(yaxis = list(title = 'Cost'), xaxis = list(title = 'Parent'), barmode = 'stack', colorway = ramp.list2) %>%
config(displayModeBar = FALSE)
这将产生以下情节:
希望有帮助.
这篇关于使用 R 在绘图中选择前 3 个父母(组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!