【问题标题】:Make values to be seen only when hovered使值仅在悬停时可见
【发布时间】:2021-12-24 05:59:19
【问题描述】:

我们能否让这些值仅在悬停时可见。示例“Toyota Corolla”仅在悬停时可见。现在所有的值都出现了

library(plotly)

data <- mtcars[which(mtcars$am == 1 & mtcars$gear == 4),]

fig <- plot_ly(data, x = ~wt, y = ~mpg, type = 'scatter', mode = 'markers',
        marker = list(size = 10))
fig <- fig %>% add_annotations(x = data$wt,
                  y = data$mpg,
                  text = rownames(data),
                  xref = "x",
                  yref = "y",
                  showarrow = TRUE,
                  arrowhead = 4,
                  arrowsize = .5,
                  ax = 20,
                  ay = -40,
                  # Styling annotations' text:
                  font = list(color = '#264E86',
                              family = 'sans serif',
                              size = 14))

fig

【问题讨论】:

标签: r r-plotly


【解决方案1】:

若要添加行名称/汽车类型以便当您将鼠标悬停在该点上时它们会出现,您只需添加text 并在hoverinfo 中使用它

在您的示例中,您可以使用rownames() 获取汽车类型并将它们添加到text,然后hoverinfo 可以使用它

fig <- plot_ly(data, x = ~wt, y = ~mpg, type = 'scatter', mode = 'markers',
               marker = list(size = 10), text = rownames(data), hoverinfo = "text")

但是,如果您没有将汽车名称作为行名,而只是作为数据框中的一列,则可以直接将它们应用到 text,然后 hoverinfo 可以使用它

#Not required. Just used to create a column with car names#
data$cars <- rownames(data)

然后您可以将新列用作text

fig <- plot_ly(data, x = ~wt, y = ~mpg, type = 'scatter', mode = 'markers',
               marker = list(size = 10), text = data$cars, hoverinfo = "text")

这两种方法都会给你以下结果

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 2017-10-19
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2013-07-15
    • 2017-10-05
    相关资源
    最近更新 更多