I have a simple data frame:
seq <- 1:10
name <- c(paste0("company",1:10))
value <- c(250,125,50,40,40,30,20,20,10,10)
d <- data.frame(seq,name,value)
And I want to plot it this way:
require(ggplot2)
ggplot(data = d,aes(x=seq,y=value))+geom_line() + geom_point()
Now I want to use plotly, mostly to be able, when mousing over a point, to get other information than the value, such as the company name. I try this :
require(plotly)
ggplotly()
which get me a tooltip, but with only seq and value. I tried the option tooltip= but it's specified you can use the only variable describe in the aesthetic, and I don't use the name in my aes.
Any solution? I saw I am not the first with this problem, but I haven't found answer working with ggplotly.
Building on @UweBlock's answer, you can also create dummy aesthetics in order to display multiple labels in tooltips. I can't find where this is documented, but discovered it emperically. The dummy variables show up in the order you specify them, but priority is given to the default variables (e.g. x and y). To get around this, you can specify those variables in a separate aesthetic, as shown below:
You'll have to modify the
plotly object
to do this. Or useplot_ly()
to create the graph instead...EDIT: With the release of
plotly 4.0
the syntax will change a little bit.You don't need to modify the
plotly
object as suggested by @royr2. Just addlabel = name
as third aestheticand the tooltip will display
name
in addition toseq
andvalue
.The
ggplotly
help file says abouttooltip
parameter:So you can use the
label
aesthetic as long as you don't want to use it forgeom_text
.BTW: I've also tried
text
instead oflabel
but then
ggplot2
complainedand plotted only points. I had to add a dummy group to
geom_line
to remove the issue:(But note if you put the dummy group as fourth aesthetic inside
aes()
it will appear by default also in the tooltip.)However, I find the unofficial
text
aesthetic can become useful alongsidelabel
if you want to have different strings plotted bygeom_text
and shown in the tooltip.Edit to answer a question in comments: The
tooltip
parameter toggplotly()
can be used to control the appearance.ggplotly(tooltip = NULL)
will suppress tooltips at all.ggplotly(tooltip = c("label"))
selects the aesthetics to include in the tooltip.The unofficial
text
aesthetic allows you to introduce all the variables you want (here I usename
twice to show it):I have to add a dummy
group
aesthetic for thegeom_line
to work properly as @UweBlock suggested.At last I choose what I want to show in the tooltip (here I excluded
group
).