4

I wish to have text as labels in a plotly interactive figure and hover over these labels for more information.

However, plotly won't let me have text labels and hover text in the same line of code. I am desperately after text labels and don't wish to use a simple scatter point.

Is there a way I can fix the code below so text labels can be presented and hover text?

Thanks.

# 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))
user2716568
  • 1,866
  • 3
  • 23
  • 38

1 Answers1

5

You could do something similar to the solution suggested here, i.e. create a scatter plot just for the hovertext and add the text as annotations.

enter image description here

See the snippet below.

# 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
Community
  • 1
  • 1
Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99