简体   繁体   English

图表条形图中的颜色

[英]Color in plotly bar chart

I'm trying to generate a bar plot using plotly in R. The bars should be sorted by value and there are two classes of bars, which I want to color differently. 我正在尝试使用R中的plotly生成条形图。条形图应按值排序,并且有两类条形图,我希望颜色不同。 However, when I add the color, the bars are split into two groups, sorted within groups. 但是,当我添加颜色时,条形图分为两组,按组排序。 Any hint on how I can keep them in one group? 有关如何将它们保存在一个组中的任何提示?

Here's my code: 这是我的代码:

plotting.df = data.frame(names=c("a", "b", "c", "d", "e", "f", "g"),
                         value=c(1.9468656, 1.3867055, 1.0433950, 0.8949743, 0.3714826, 0.3605037, 0.3003954),
                         label=c("y", "n", "y", "n", "n", "n", "n"),
                         color=c("red", "black", "red", "black", "black", "black", "black"))
plotting.df$names = factor(as.character(plotting.df$names), levels=as.character(plotting.df$names)[order(plotting.df$value, decreasing=TRUE)])
plotting.df = plotting.df[order(plotting.df$value, decreasing=TRUE), ]
plot_ly(plotting.df, type="bar", x=names, y=value, 
        name="Comp a", 
        hoverinfo="text", text=c(paste("Name:", plotting.df$names, 
                                       "<br>Value:", signif(plotting.df$value, digits=3),
                                       "<br>Label:", plotting.df$label)),
        color=color)

And an example: 一个例子:

在此输入图像描述

It's a bit of a hack but this 'solves' the specific issue asked. 这有点像黑客,但这“解决”了具体的问题。

Starting with your data frame: 从您的数据框开始:

    library(tidyr)

    plotting.df2 <- plotting.df %>%
      spread(names, value, fill = NA) %>%
      gather("names", "value", a:g)

    plot_ly(plotting.df2, 
        type="bar", 
        x=names, 
        y=value, 
        name="Comp a", 
        hoverinfo="text", 
        color=color,
        text=c(paste("Name:", plotting.df$names, 
                     "<br>Value:", signif(plotting.df$value, digits=3),
                     "<br>Label:", plotting.df$label))) %>%
    layout(barmode = "stack")

Basically this method is creating a data point for each combination of name and color, filled with NAs. 基本上,这种方法是为名称和颜色的每个组合创建一个数据点,并填充NA。 Then these are stacked in the plot. 然后将这些堆叠在图中。

This 'solution' is probably useless if you want to actually stack data values later on, but hopefully this hack will get someone out of a similar hole at least temporarily. 如果你想在以后实际堆叠数据值,这个“解决方案”可能毫无用处,但希望这个黑客能够让某人至少暂时离开类似的漏洞。

EDIT: This example uses plotly 3.xx If you use plotly 4.xx or above, this code may not work as is. 编辑:此示例使用plotly 3.xx如果使用plotly 4.xx或更高版本,此代码可能无法正常工作。 See here for more details: https://www.r-bloggers.com/upgrading-to-plotly-4-0-and-above/ 有关详细信息,请参阅此处: https//www.r-bloggers.com/upgrading-to-plotly-4-0-and-above/

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

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