R:格式化情节悬停文本

Posted

技术标签:

【中文标题】R:格式化情节悬停文本【英文标题】:R: formatting plotly hover text 【发布时间】:2021-04-02 15:45:43 【问题描述】:

我正在使用 R 编程语言。我试图学习如何在 3d 绘图对象中自定义悬停文本,如下所示:https://rstudio-pubs-static.s3.amazonaws.com/441420_9a7c15988f3c4f59b2d828eb87ba1634.html

最近,我学会了如何为我模拟的一些数据创建一个 3d 绘图对象:

  library(Rtsne)
    library(dplyr)
    library(ggplot2)
    library(plotly)
    library(caret)
    library(randomForest)
    
  #data
a = iris
a <- unique(a)

#create two species just to make things easier
s <- c("a","b")
species<- sample(s , 149, replace=TRUE, prob=c(0.3, 0.7))
a$species = species
a$species = as.factor(a$species)

#split data into train/test, and then random forest 

index = createDataPartition(a$species, p=0.7, list = FALSE)
train = a[index,]
test = a[-index,]

rf = randomForest(species ~ ., data=train, ntree=50, mtry=2)

#have the model predict the test set
pred = predict(rf, test, type = "prob")
labels = as.factor(ifelse(pred[,2]>0.5, "a", "b"))
confusionMatrix(labels, test$species)


#tsne algorithm
tsne_obj_3 <- Rtsne(test[,-5], perplexity=1, dims=3)
df_m2 <- as.data.frame(tsne_obj_3$Y)

df_m2$labels = test$species

df_m2$color = ifelse(df_m2$labels == "a", "red","blue")
df_m2$petal_length = test$Petal.Length

axis_1 = df_m2$V1
axis_2 = df_m2$V2
axis_3 = df_m2$V3

plot_ly(x=as.vector(axis_1),
        y=as.vector(axis_2), 
        z=axis_3, 
        type="scatter3d",
        mode="markers", 
        name = "Obs", 
        marker = list(size = 3)) %>% 
   add_mesh(x=as.vector(axis_1), 
            y=as.vector(axis_2), 
            z=df_m2$pred, 
            type = "mesh3d", 
            name = "Preds")

现在,我正在尝试自定义这个 plotly 对象,以便当您将鼠标移到每个点上时会出现不同的标签,并且与给定类对应的点都具有相同的颜色:

p <- plot_ly(type = 'scatter3d', mode = 'markers', colors = "Accent", color = df_m2$color) %>%
  add_trace(
    x = df_m2$V1,
    y = df_m2$V2,
    z = df_m2$V3,
    marker = list(
      size = 3),
    name = df_m2$labels,
    text = paste("Species: ", df_m2$labels ; "Width: ", df_m2$petal.width ; "color: ", df_m2$color" ),
    showlegend = T
  )  %>%


   add_mesh(x=as.vector(axis_1), 
            y=as.vector(axis_2), 
            z=df_m2$pred, 
            type = "mesh3d", 
            name = "Preds")
  %>% 
  layout(
    title = "none",
    titlefont = list(
      size = 10
    ),
    paper_bgcolor = "#fffff8",
    font = t,
    xaxis = list(
      zeroline = F
    ),
    yaxis = list(
      hoverformat = '.2f',
      zeroline = F
    )
  )  

p

但是,这里有一个错误。有人可以告诉我我做错了什么吗?

谢谢

【问题讨论】:

您的 plot_ly-call 的第 9 行有一个错字:text = paste("Species: ", df_m2$labels ; "Width: ", df_m2$petal.width ; "color: ", df_m2$color" )。将最后一个 " 留在最后。 我试过了,我认为还有更多错误。我会继续调试它 【参考方案1】:

不确定您究竟想对预测的类做什么,但可能是这样的? (颜色对应真实物种,鼠标悬停也显示预测)。

library(reprex)
reprex(
suppressPackageStartupMessages(invisible(
  lapply(c("Rtsne", "dplyr", "ggplot2", "plotly", "caret", "randomForest"),
         require, character.only = TRUE)))

#data
a <- unique(iris)

#create two species just to make things easier
set.seed(123)
a$species <- factor(sample(c("a", "b"), 149, replace=TRUE, prob=c(0.3, 0.7)))

#split data into train/test, and then random forest 
index = createDataPartition(a$species, p=0.7, list = FALSE)
train = a[index,]
test = a[-index,]

rf <- randomForest(species ~ ., data=train, mtry=2)

#have the model predict the test set
pred <- predict(rf, test, type = "prob")
labels <- predict(rf, test)
confusionMatrix(labels, test$species)

#tsne algorithm
tsne_obj_3 <- Rtsne(test[,-5], perplexity=1, dims=3)
df_m2 <- as.data.frame(tsne_obj_3$Y)

df_m2$labels = toupper(test$species)
df_m2$pred <- labels # you did not define but call pred in plot_ly call
df_m2$color = ifelse(df_m2$labels == "A", "red", "blue")
df_m2$petal_length = test$Petal.Length

axis_1 <- df_m2$V1
axis_2 <- df_m2$V2
axis_3 <- df_m2$V3

plot_ly(type = 'scatter3d', mode = 'markers', colors = c("blue", "red"), 
        color = df_m2$color) %>%
  add_trace(
    x = df_m2$V1,
    y = df_m2$V2,
    z = df_m2$V3,
    marker = list(size = 3),
    name = df_m2$pred,
    text = paste0("Species: ", df_m2$labels, "; Length: ",df_m2$petal_length, "; color: ", df_m2$color),
    showlegend = TRUE)  %>%

   add_mesh(x=as.vector(axis_1), 
            y=as.vector(axis_2), 
            z=axis_3, # not sure what z you want here
            type = "mesh3d", 
            name = "Preds") %>% 
  
  layout(
    title = "none",
    titlefont = list(size = 10),
    paper_bgcolor = "#fffff8",
                 font = "Open Sans",
                 xaxis = list(zeroline = FALSE),
                 yaxis = list(hoverformat = '.2f', zeroline = FALSE)
    )

【讨论】:

感谢您的回答!我尝试了几个小时来修复这些错误!对于这一切,我感激不尽!我只有一件事感到困惑。我认为整个“3d 图”应该有 3 种颜色:“specie A”的所有点的颜色,“speciesB”的所有点的颜色,以及所有其他表面的另一种颜色。在答案中,有 4 种颜色:红色、蓝色、棕色和粉红色。是否可以去除棕色或粉红色?我遇到的另一个问题:当我将鼠标移到棕色和粉红色区域时,我会弹出“不可见点”的弹出窗口。这是正确的吗? 您可以将facecolor 用于您的网格,例如添加到add_mesh 函数, facecolor=rep("blue", 55), opacity = 0.1,或类似的东西。 @user12728748 :你能看看我的问题吗? ***.com/questions/68242473/… 谢谢!

以上是关于R:格式化情节悬停文本的主要内容,如果未能解决你的问题,请参考以下文章

在情节中悬停文本问题

R情节,当鼠标悬停在图上时正常光标

Plotly:悬停文本字段中的日期格式问题

如何在 r 汽车包中的后续情节的完整性中以适当的格式在 x 轴上绘制日期?

Plotly:如何在带注释的热图中舍入显示文本但在悬停时保持完整格式?

编织为pdf时,R markdown链接未格式化为蓝色