首页 > 解决方案 > 在 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)
}

标签: r3dplotlypca

解决方案


使用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)
}

推荐阅读