我正在尝试显示带有错误条的条形图。当我添加颜色变量时,错误条显示在错误的条上。
df <- data_frame(label = c("Step 1", "Step 2", "Step 3", "Step 4"),
Action = c("DISPENSE", "WAIT", "DISPENSE", "WAIT" ),
Avg = c(1.65, 3.88, 1.19, 23.09),
StdDev = c(0.80, 7.54, 0.11, 14.63))
p1 <- plot_ly(df, type = "bar", orientation = 'h',
y = ~label, x = ~Avg, color = ~Action,
error_x = list(type = "data", array = ~StdDev, color = "#000000"),
text = ~paste0(Avg," (+/- ",StdDev,")"), hoverinfo = "text")
p2 <- plot_ly(df, type = "bar", orientation = 'h',
y = ~label, x = ~Avg,
error_x = list(type = "data", array = ~StdDev, color = "#000000"),
text = ~paste0(Avg," (+/- ",StdDev,")"), hoverinfo = "text")
subplot(p1, p2, nrows=2)
这是情节的输出:
我希望图表通过Action进行着色,就像在p1
中一样,但是要正确地为每行分配误差线,就像在p2
中一样。
我为error_x
参数尝试了多种形式,但没有成功:
error_x = ~list(type = "data", array = StdDev, color = "#000000")
error_x = ~list(type = "array", array = StdDev, color = "#000000")
error_x = list(type = "array", array = ~StdDev, color = "#000000")
我怀疑这与this problem类似,或者它们都是由相同的错误引起的。我无法实施他们的解决方案。
答案 0 :(得分:0)
将数组传递给color
不仅会产生彩色条,还会引起更多更改,还会将数据分成多条迹线。
如果要同时使用不同的颜色和不同的迹线,除了手动创建迹线外,我没有其他解决方案。
在第一个图形中,颜色是手动分配的,在第二个图形中,为每个唯一的Action
值创建一个新轨迹。
library(tibble)
library(plyr)
library(plotly)
df <- data_frame(label = c("Step 1", "Step 2", "Step 3", "Step 4"),
Action = c("DISPENSE", "WAIT", "DISPENSE", "WAIT" ),
Avg = c(1.65, 3.88, 1.19, 23.09),
StdDev = c(0.80, 7.54, 0.11, 14.63))
color_choices <- list("#8DA0CB", "#59C5A3")
colors <- mapvalues(df$Action, unique(df$Action), color_choices)
p1 <- plot_ly(df, type = "bar", orientation = 'h',
y = ~label, x = ~Avg,
error_x = list(type = "data", array = ~StdDev),
text = ~paste0(Avg," (+/- ",StdDev,")"), hoverinfo = "text",
marker = list(color = colors))
p2 <- plot_ly()
names(color_choices) <- unique(df$Action)
for (action in unique(df$Action))
{
df_filtered <- filter(df, Action == action)
p2 <- plotly::add_bars(p2, orientation = 'h',
y = df_filtered$label, x = df_filtered$Avg,
error_x = list(type = "data", array = df_filtered$StdDev),
text = ~paste0(df_filtered$Avg," (+/- ", df_filtered$StdDev, ")"),
color = color_choices[action][[1]],
hoverinfo = "text",
name = action)
}
subplot(p1, p2, nrows=2)