堆叠堆积的条形图:如何控制每个堆积中条形的顺序 [英] Stacked bar graphs in plotly: how to control the order of bars in each stack

查看:707
本文介绍了堆叠堆积的条形图:如何控制每个堆积中条形的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按顺序订购堆积的条形图,但不遵守我在数据框中传递它的顺序.

I'm trying to order a stacked bar chart in plotly, but it is not respecting the order I pass it in the data frame.

最好使用一些模拟数据来显示:

It is best shown using some mock data:

library(dplyr)
library(plotly)
cars <- sapply(strsplit(rownames(mtcars), split = " "), "[", i = 1)
dat <- mtcars
dat <- cbind(dat, cars, stringsAsFactors = FALSE)
dat <- dat %>% 
         mutate(carb = factor(carb)) %>%
         distinct(cars, carb) %>% 
         select(cars, carb, mpg) %>% 
         arrange(carb, desc(mpg))
plot_ly(dat) %>% 
  add_trace(data = dat, type = "bar", x = carb, y = mpg, color = cars) %>%  
  layout(barmode = "stack") 

生成的图不遵守顺序,我希望将最大mpg的汽车堆放在每个气缸组的底部.有什么想法吗?

The resulting plot doesn't respect the ordering, I want the cars with the largest mpg stacked at the bottom of each cylinder group. Any ideas?

推荐答案

正如已经在此处指出的那样,问题是由于在用于颜色分组的列中有重复的值(在本例中为cars)而引起的.如前所述,可以通过按唯一名称列对颜色进行分组来纠正条形的排序.但是,这样做会产生一些不良的副作用:

As already pointed out here, the issue is caused by having duplicate values in the column used for color grouping (in this example, cars). As indicated already, the ordering of the bars can be remedied by grouping your colors by a column of unique names. However, doing so will have a couple of undesired side-effects:

  1. 来自同一制造商的不同型号的汽车将以不同的颜色显示(不是您要的颜色,而是要由制造商着色)
  2. 图例中的条目将比您想要的要多,即每种型号的汽车都有一个条目,而不是每个制造商的一个条目.

我们可以通过以下方法来解决这一问题:a)从永远不会显示的虚拟跟踪中创建图例(在下面的代码中为add_trace(type = "bar", x = 0, y = 0...),以及b)使用colors=参数为每个类别手动设置颜色.我在下面使用彩虹调色板来说明原理.您可能希望自己选择更吸引人的颜色.

We can hack our way around this by a) creating the legend from a dummy trace that never gets displayed (add_trace(type = "bar", x = 0, y = 0... in the code below), and b) setting the colors for each category manually using the colors= argument. I use a rainbow pallette below to show the principle. You may like to select sme more attractive colours yourself.

dat$unique.car <- make.unique(as.character(dat$cars))
dat2 <- data.frame(cars=levels(as.factor(dat$cars)),color=rainbow(nlevels(as.factor(dat$cars))))
dat2[] <- lapply(dat2, as.character)
dat$color <- dat2$color[match(dat$cars,dat2$cars)]

plot_ly() %>% 
  add_trace(data=dat2, type = "bar", x = 0, y = 0, color = cars, colors=color, showlegend=T) %>%  
  add_trace(data=dat, type = "bar", x = carb, y = mpg, color = unique.car, colors=color, showlegend=F, marker=list(line=list(color="black", width=1))) %>%  
  layout(barmode = "stack", xaxis = list(range=c(0.4,8.5))) 

这篇关于堆叠堆积的条形图:如何控制每个堆积中条形的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆