r - 将特定图例添加到 R plotly 图表
问题描述
有人知道是否可以将以下类型的图例添加到 R plot_ly 图表中?
请在下面找到一个可复制的示例
在这个例子中,条形颜色取决于速度值:我想打印上面提到的图例,而不仅仅是得到“trace 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)
非常感谢 !
解决方案
您可以使用图例的名称创建一个新列。并将因子重新排序为从低 (0 - 0.8) 到高 (> 1.5)。
你可以试试这个:
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))
推荐阅读
- python - 如何修复 AttributError:模块“x”没有属性
- javascript - JavaScript 如何等到元素存在?
- sql - SQL-server 中的左连接
- azure-functions - Azure函数Nodejs的文件夹结构
- java - 我如何处理带有计数的 ArrayList,并按函数分组,具有字符串数组的值
- python - 从xml数据中获取第二个标签值
- java - 如何从 RECYCLERVIEW 中的选定项目中获取 TEXT VIEW 值
- mysql - NOT IN 不考虑
- python - python - 从文件中提取某些文本数据的正则表达式
- python - 使用 python 和 Gmail 作为提供者发送电子邮件。不工作