简体   繁体   English

Plotly:如何自定义堆叠条形图中的颜色?

[英]Plotly: How to customize colors in a stacked bar chart?

I would like to ask you if you could help me in customizing of colors in a stacked bar chart created by plotly.我想问你是否可以帮助我在 plotly 创建的堆叠条形图中自定义颜色。

The problem is following - I have to recreate a dashboard (from an excel file to a html file).问题如下 - 我必须重新创建一个仪表板(从 excel 文件到 html 文件)。 A part of the dashboard is a chart providing us with information about early production of each entity.仪表板的一部分是一个图表,为我们提供有关每个实体的早期生产的信息。 The chart is a stacked bar chart type by plotly.该图表是 plotly 的堆叠条形图类型。 As each entity is defined by a specific color (defined in RGB) throughout whole dashboard, I need to keep these colors in the donut chart as well.由于整个仪表板中每个实体都由特定颜色(以 RGB 定义)定义,因此我也需要将这些颜色保留在圆环图中。 But there is a problem.但有一个问题。 I always get the following warning:我总是收到以下警告:

Warning message: In RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8 Returning the palette you asked for with that many colors警告消息:在 RColorBrewer::brewer.pal(N, "Set2") 中:n 太大,调色板 Set2 允许的最大值为 8 返回您要求的具有这么多颜色的调色板

and the resulting donut chart containts only one Entity with a not-specified color.生成的圆环图仅包含一个未指定颜色的实体。 Also, the colors in the legend are not those which are defined.此外,图例中的颜色不是定义的颜色。

Any idea what to do with it?知道如何处理它吗? Thank you so much in advance.非常感谢你提前。

Code:代码:

library(dplyr)
library(plotly)

dt <- as.data.frame(matrix(ncol = 13, nrow = 19))
colnames(dt) <- c("Entity", month.abb)

for (i in 1:nrow(dt)) {
  dt[i, 1] <- paste("Entity", i, sep="")
  dt[i, -1] <- floor(runif(12, min=0, max=100))
}

# assign colors to entities

dt$"EntityColor" <- c("#074263", "#0B5394", "#3D85C6", "#6D9EEB", "#A4C2F4", "#CFE2F3", "#5B0F00", "#85200C", "#A61C00", "#CC4125", "#DD7E6B", "#E6B8AF", "#F8CBAD", "#F4CCCC", "#274E13", "#38761D", "#E06666", "#CC0000", "#20124D")

data.table::melt(dt) %>%

  plot_ly(x = ~variable,
          y = ~value,
          type = "bar",
          color = ~Entity,
          marker = list(colors = ~EntityColor)
  ) %>%

  layout(yaxis = list(title = ""),
         xaxis = list(title = ""),
         barmode = 'stack')

Plot:阴谋:

在此处输入图像描述

Refined approach after comments:评论后的改进方法:

Since the colors turned out to be a bit tricky (see initial suggestion below) I had to break the whole thing down and use a combination of plot_ly() and add_traces() in a loop to make sure that the plotly settings did not apply colors in the wrong order.由于颜色有点棘手(请参阅下面的初步建议)我不得不将整个事情分解并在循环中使用plot_ly()add_traces()的组合以确保 plotly 设置不应用颜色以错误的顺序。 The following plot should be exactly what you're looking for.下面的情节应该正是你要找的。

Plot:阴谋:

在此处输入图像描述

Note that I've appended a continuous numerical column ID .请注意,我附加了一个连续的数字列ID Why?为什么? Because you wanted the names in alphabetical order, and the rows are added to the plot in the order they appear in your source.因为您希望名称按字母顺序排列,并且行会按照它们在您的源代码中出现的顺序添加到绘图中。 And It's a bit tricky since a straight up ordering using dt %>% arrange((Entity)) would give you Entity1, Enitity10, Entity11 etc. Let me know if you'd like to adjust this in any other way.这有点棘手,因为使用dt %>% arrange((Entity))直接向上排序会给你Entity1, Enitity10, Entity11等。如果你想以任何其他方式调整它,请告诉我。

Code:代码:

library(dplyr)
library(plotly)

# data
set.seed(123)

dt <- as.data.frame(matrix(ncol = 13, nrow = 19))
colnames(dt) <- c("Entity", month.abb)
for (i in 1:nrow(dt)) {
  dt[i, 1] <- paste("Entity", i, sep="")
  dt[i, -1] <- floor(runif(12, min=0, max=100))
}

# assign colors to entities
dt$"EntityColor" <- c("#074263", "#0B5394", "#3D85C6", "#6D9EEB", "#A4C2F4", "#CFE2F3", "#5B0F00", "#85200C", "#A61C00", "#CC4125", "#DD7E6B", "#E6B8AF", "#F8CBAD", "#F4CCCC", "#274E13", "#38761D", "#E06666", "#CC0000", "#20124D")



# sort data
dt$ID <- seq.int(nrow(dt))
dt <- dt %>% arrange(desc(ID))


# specify month as factor variable to ensure correct order
months=names(dt)[2:13]
months<- factor(months, levels = c(months))

# plotly setup
p <- plot_ly(type = 'bar')

# add trace for each entity
nrows = nrow(dt)
for(i in 1:nrows) {
    p <- p %>% add_trace(x=months, y = unlist(dt[i,2:13], use.names=F), type = 'bar',
                         #name = paste(dt[i,1], dt[i,14], sep = "_"),
                         name = dt[i,1],
                         type = 'bar',  
                         marker=list(color = dt[i,14])) %>%
       layout(barmode = 'stack')

}

# Edit layout
p <- p %>% layout(title = list(xanchor='right', text='Correct colors, orderered legend'),
                  yaxis = list(title = ''),
                  xaxis = list(title = 'month'))
p

Color correctness verification:颜色正确性验证:

在此处输入图像描述

Initial suggestion初步建议

Here's an initial suggestion.这是一个初步的建议。 First of all, color = ~Entity has got to go.首先, color = ~Entity必须离开。 And marker = list(color = ~EntityColor) versus marker = list(colors = ~EntityColor) gives two different results. marker = list(color = ~EntityColor)marker = list(colors = ~EntityColor)给出了两个不同的结果。 What makes matters even stranger is that the pie chart documentation uses:奇怪的是饼图文档使用:

marker = list(colors = colors, ...)

... and the bar chart documentation uses: ...并且条形图文档使用:

marker = list(color = c('rgba(204,204,204,1)', 'rgba(222,45,38,0.8)', ...)

...without the s at the end of color . ...没有color末尾的s

Either way, you should test both marker = list(color = ~EntityColor) and marker = list(colors = ~EntityColor) and see what's correct for you.无论哪种方式,您都应该测试marker = list(color = ~EntityColor)marker = list(colors = ~EntityColor)并查看适合您的方法。

Plot:阴谋:

在此处输入图像描述

Code:代码:

dt <- as.data.frame(matrix(ncol = 13, nrow = 19))
colnames(dt) <- c("Entity", month.abb)

for (i in 1:nrow(dt)) {
  dt[i, 1] <- paste("Entity", i, sep="")
  dt[i, -1] <- floor(runif(12, min=0, max=100))
}

# assign colors to entities

dt$"EntityColor" <- c("#074263", "#0B5394", "#3D85C6", "#6D9EEB", "#A4C2F4", "#CFE2F3", "#5B0F00", "#85200C", "#A61C00", "#CC4125", "#DD7E6B", "#E6B8AF", "#F8CBAD", "#F4CCCC", "#274E13", "#38761D", "#E06666", "#CC0000", "#20124D")

data.table::melt(dt) %>%

  plot_ly(x = ~variable,
          y = ~value,
          name= ~Entity,
          type = "bar",
          #color = ~Entity,
          marker = list(colors = ~EntityColor)
  ) %>%

  layout(yaxis = list(title = ""),
         xaxis = list(title = ""),
         barmode = 'stack')

Take a look and see how it works out for you.看看它是如何为你工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM