更改R中的图例标题

时间:2018-07-05 14:07:41

标签: r 3d plotly pca

我正在使用以下代码在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)
}

1 个答案:

答案 0 :(得分:0)

name使用add_trace参数。我在下面模拟了一些数据,但是将来要记住,使用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)
}