[英]Add specific legend to R plotly chart
Does someone know how if it is possible to add the following kind of legend to a R plot_ly chart ? 有人知道如何在R plot_ly图表中添加以下图例吗?
Please find a reproductible example below 请在下面找到可复制的示例
In this example, bar colors depends on velocity value: I would like to print the legend as mentionned above and not only get "trace 0" ... 在此示例中,条形颜色取决于速度值:我想如上所述打印图例,而不仅获得“迹线0” ...
library(plotly)
library(data.table)
example_data <- data.table(x = c(1,2,3,4,5,6), y = c(7,9,4,3,8,9), velocity = c(0.6,1.4,5,4,0.2,1.1))
example_data$color <- cut(example_data$velocity,breaks = c(0,0.8,1.2,1.5,10),labels = c("lightgreen","darkgreen","yellow","red"))
plot_ly(data = example_data, x = ~ x,y = ~y ,color = ~ I(color),type = "bar") %>%
layout(showlegend = TRUE)
Thanks a lot ! 非常感谢 !
You can create a new column with the names for the legend. 您可以使用图例名称创建一个新列。 And reorder the factor to be from low (0 - 0.8) to high (> 1.5). 并将因子从低(0-0.8)重新排序为高(> 1.5)。
You can try this: 您可以尝试以下方法:
example_data <- data.table(x = c(1,2,3,4,5,6), y = c(7,9,4,3,8,9), velocity = c(0.6, 1.4, 5, 4, 0.2, 1.1),
name = c("0 - 0.8", "1.2 - 1.5", " >1.5", " >1.5", "0 - 0.8", "0.8 - 1.2"))
example_data$name <- as.factor(example_data$name)
example_data$name <- factor(example_data$name, levels = c("0 - 0.8", "0.8 - 1.2", "1.2 - 1.5", " >1.5"))
pal <- c("lightgreen", "darkgreen", "yellow", "red")
plot_ly(data = example_data, x = ~ x,y = ~y ,color = ~as.factor(name), colors = ~pal, type = "bar") %>%
layout(showlegend = TRUE, legend = list(orientation = "h",
xanchor = "center",
x = 0.5, y = 7))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.