r - 在 R Plotly 中更改图例标题
问题描述
我正在使用以下代码在 Plotly - R studio 中生成带有向量的 3D 散点图。目前,图例标签显示为“迹线 1、迹线 2 等”,但我想用我自己的文本进行更改。知道如何实现这一目标吗?
#Define the data from df to be plotted, basically three columns of a data frame
x = df[,1]
y = df[,2]
z = df[,3]
#Scatter and Axis Labels
p <- plot_ly() %>%
add_trace(x=x, y=y, z=z,
type="scatter3d", mode="markers",
marker = list(color=y,
colorscale = 'Viridis',
opacity = 0.02,showscale = F)) %>%
layout(title = "TITLE",
scene = list(
xaxis = list(title = "LABEL 1"),
yaxis = list(title = "LABEL 2"),
zaxis = list(title = "LABEL 3")))
#Add Vectors to the Plot
for (k in 1:nrow(df_vector)) {
x <- c(0, df_vector[k,1])
y <- c(0, df_vector[k,2])
z <- c(0, df_vector[k,3])
p <- p %>% add_trace(x=x, y=y, z=z,
type="scatter3d", mode="lines",
line = list(width=8),
opacity = 1)
}
解决方案
使用name
参数来add_trace
。我在下面模拟了一些数据,但以后请记住,使用 (eg) 包含易于阅读的示例数据会很有帮助dput
。
library(plotly)
## Reproducible by setting RND seed
set.seed(42)
## Define the data from df to be plotted, basically three columns of a data frame
df <- data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100))
## Scatter and Axis Labels
p <- plot_ly(df) %>%
add_trace(x=~x, y=~y, z=~z,
type="scatter3d", mode="markers",
name = "markers"
# ,
# marker = list(
# colorscale = 'Viridis',
# opacity = 0.02,showscale = F)
) %>%
layout(title = "TITLE",
scene = list(
xaxis = list(title = "LABEL 1"),
yaxis = list(title = "LABEL 2"),
zaxis = list(title = "LABEL 3")))
#Add Vectors to the Plot
for (k in 1:nrow(df[1:3, ])) {
x <- c(0, df[k, 1])
y <- c(0, df[k, 2])
z <- c(0, df[k, 3])
p <- p %>% add_trace(x=x, y=y, z=z,
name = paste("my trace name", k),
type="scatter3d", mode="lines",
line = list(width=8),
opacity = 1)
}
推荐阅读
- tensorflow - Tensorflow 上的 CPU 使用率高
- jboss - JBoss LiveReload 被弃用的原因是什么,还有其他选择吗?
- c# - mqtt 客户端总是不接收消息
- vue.js - 使用带有 weex 的 vue 路由器
- bash - 在 shell 脚本中检测 GTK3 的可用性
- azure - 不区分大小写的 Azure 搜索
- java - 为什么我们不能在java中制作动态数组
- amazon-web-services - 资源暂时不可用 - TCP 5985
- angular - Angular 4 recaptcha - 意外令牌 <
- sql - MSSQL - 授予对除一个表之外的所有表的选择权限