Format hover data labels Plotly R

Mavic picture Mavic · Mar 21, 2018 · Viewed 7.2k times · Source

I am trying to format the data labels that appear when I hover over part of a chart I have created using Plotly. The label is currently showing like this. I would like for the label to only show profit.

My code for creating the plot is:

output$monthlyProfits <- renderPlotly({
ggplot(profitTemp, aes(x = Date, y = Profit)) + geom_line(aes(text=Profit), 
colour = "Blue") 

How do I format the data label so that it will not show the X axis and only show the Y axis (profit)? I have tried with aes(text=Profit) but the X axis still shows.

Any help would be greatly appreciated.

Answer

missuse picture missuse · Mar 21, 2018

It is more flexible to customize the plots that are directly made in plotly, however the requested operation is also possible using ggplotly. Here is an example on the iris data set:

library(plotly)
library(ggplot)

To define the hover info:

plot_ly(data = iris,
        x = ~Sepal.Length,
        y = ~Petal.Length,
        color = ~Species,
        hoverinfo = 'text',
        text = ~Species)

enter image description here

to do so with ggplotly leave the text argument blank when calling ggplot:

z <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species))+
  geom_point() 

and set the argument tooltip to ggplotly:

ggplotly(z, tooltip="Species")

enter image description here

compared to:

z <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species))+
  geom_point(aes(text = Species)) 

ggplotly(z)

enter image description here

EDIT: custom text:

plot_ly(data = iris,
        x = ~Sepal.Length,
        y = ~Petal.Length,
        color = ~Species,
        hoverinfo = 'text',
        text = ~paste(Species,
                      '</br></br>', Petal.Length))

enter image description here