条形图中的颜色 [英] Color in plotly bar chart
问题描述
我正在尝试使用R中的plotly生成条形图.条形图应按值排序,并且有两类条形图,我想用不同的颜色进行着色.但是,当我添加颜色时,条形图被分为两组,并按组进行排序.关于如何将它们分组的任何提示?
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. 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?
这是我的代码:
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)
还有一个例子:
推荐答案
有点麻烦,但这可以解决"所要求的特定问题.
It's a bit of a hack but this 'solves' the specific issue asked.
从数据框开始:
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")
基本上,此方法是为名称和颜色的每种组合创建一个数据点,并用NA填充.然后将它们堆叠在图中.
Basically this method is creating a data point for each combination of name and color, filled with NAs. 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.
本示例使用plotly
3.x.x.如果您使用plotly
4.x.x或更高版本,则此代码可能无法按原样工作.详情请参阅此处: https://www. r-bloggers.com/upgradeing-to-plotly-4-0-and-above/
This example uses plotly
3.x.x. If you use plotly
4.x.x or above, this code may not work as is. See here for more details: https://www.r-bloggers.com/upgrading-to-plotly-4-0-and-above/
这篇关于条形图中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!