可以在 plotly 中使用文本标签和悬停文本吗?

Can text labels and hover text be used in plotly?

我希望在情节互动的图形中将文本作为标签并将鼠标悬停在这些标签上以获取更多信息。

但是,plotly 不允许我在同一行代码中使用文本标签和悬停文本。我拼命寻找文本标签,不想使用简单的散点。

有没有办法修复下面的代码,以便可以显示文本标签和悬停文本?

谢谢。

# Load packages
require(ggplot2)
require(plotly)
# Example data
data(iris)
str(iris)
# Create new columns - with more information
iris$Symbol <- c("Se", "Ve", "Vi")[iris$Species]
iris$PlantedBy <- c("Bruce", "Joe", "Eliza")[iris$Species]
# Create in ggplot
ggplot(iris, aes(x = Sepal.Length, y =Sepal.Width, colour = Species, 
                          label = Symbol)) +
  geom_text(fontface = "bold", size = 6) +
  theme_classic() +
  theme(legend.position = "none")
# Plotly - point with hover text
plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter',
        mode = 'text',
        text = ~Symbol)
# Plotly - point with hover text (does not work)
plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter',
        mode = 'text',
        text = ~Symbol,
        hoverinfo = 'text',
        text = ~paste('Species: ', Species, 
                           '</br> Planted by: ', PlantedBy))

您可以执行类似于建议的解决方案 的操作,即仅为悬停文本创建散点图并将文本添加为​​注释。

请参阅下面的代码段。

# Load packages
require(plotly)
# Example data
data(iris)

# Create new columns - with more information
iris$Symbol <- c("Se", "Ve", "Vi")[iris$Species]
iris$PlantedBy <- c("Bruce", "Joe", "Eliza")[iris$Species]

# Create scatter plot with no markers but hovertext
p <- plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, 
            type = 'scatter',
        mode = 'markers',
        hoverinfo = 'text',
        text = ~paste('Species: ', Species, 
                      '</br> Planted by: ', PlantedBy),
        marker = list(size=1)) %>%
#add annotations for text symbols
add_annotations(
    x= iris$Sepal.Length,
    y = iris$Sepal.Width,
    text = iris$Symbol,
    showarrow = F,
    xref = "x",
    yref = "y"
    )
p