Mavic
Mavic

Reputation: 153

Format hover data labels Plotly R

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.

Upvotes: 7

Views: 11595

Answers (2)

N. Maks
N. Maks

Reputation: 666

To your second question in the comments (sorry for not leaving a comment - lacking the reputation to do so):

just supply a vector to the tooltip attribute, e.g.

ggplotly(produceMonthlyPlot, tooltip=c("QuantitySold","Product"))

With that you can control what should be displayed and what not.

Upvotes: 0

missuse
missuse

Reputation: 19716

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

Upvotes: 9

Related Questions