How to choose variable to display in tooltip when using ggplotly?
You don't need to modify the plotly
object as suggested by @royr2. Just add label = name
as third aesthetic
ggplot(data = d, aes(x = seq, y = value, label = name)) + geom_line() + geom_point()
and the tooltip will display name
in addition to seq
and value
.
The ggplotly
help file says about tooltip
parameter:
The default, "all", means show all the aesthetic mappings (including the unofficial "text" aesthetic).
So you can use the label
aesthetic as long as you don't want to use it for geom_text
.
BTW: I've also tried text
instead of label
ggplot(data = d, aes(x = seq, y = value, text = name)) + geom_line() + geom_point()
but then ggplot2
complained
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
and plotted only points. I had to add a dummy group to geom_line
to remove the issue:
ggplot(data = d, aes(x = seq, y = value, text = name)) + geom_line(group = 1) + geom_point()
(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 alongside label
if you want to have different strings plotted by geom_text
and shown in the tooltip.
Edit to answer a question in comments:
The tooltip
parameter to ggplotly()
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.
How to choose a variable to display via the tooltip of ggplotly
You need to set the tooltip
argument with a vector of variables/aesthetics of the ggplot
object (e.g. x, y, size, fill, colour...), not columns from your original dataframe (which is what you did).
You are mapping the values of z
to text
in geom_point
(which does not exist in ggplot, so you should be getting a warning). So just set tooltip = "text"
(note that the blue points will have no tooltips in this case, because you did not set the text
aesthetic there)
p = df %>% ggplot() + geom_point(aes(t, x, text = paste(z)), color = "red") +
geom_point(aes(t, y), color = "blue")
ggplotly(p , tooltip = "text")
From the help page of ggplotly
(you can read this by typing ? ggplotly
in the R console)
tooltip
a character vector specifying which aesthetic mappings to show in the tooltip. The default, "all", means show all the aesthetic mappings (including the unofficial "text" aesthetic). The order of variables here will also control the order they appear. For example, use tooltip = c("y", "x", "colour") if you want y first, x second, and colour last.
EDIT: with geom_line
When you use the unofficial text
aesthetic in geom_line
it messes up with the grouping of the points (see discussion in the link at the beginning of the question). One fix for this is to explicitly tell geom_line
to group all points together by adding the group=1
parameter.
p = df %>% ggplot() + geom_line(aes(t, x, text = paste(z), group=1), color = "red") +
geom_line(aes(t, y), color = "blue")
ggplotly(p , tooltip = "text")
Changing the tooltip in ggplotly
Try this
df <- cars
names(df) <- c("Data1", "Data2")
yy <- names(df)[2]
### define what you want to display in tooltip
text <- paste("Data2:",df$Data2, "\nData1:", df$Data1)
gg <- ggplot(df) +
geom_point(aes(x = Data1, y = reorder(Data2, Data1), text=text)) + labs(y=yy)
ggplotly(gg,tooltip = c("text"))
how to show variable name on barchart tooltip when bars are ordered by value in ggplotly
One possible solution will be to not use reorder
in ggplot
but instead reorder your x axis before passing it in ggplot
such as:
g=df %>% arrange(n) %>%
mutate(category = factor(category, unique(category))) %>%
ggplot(aes(x=category, y=n, fill=subCategory))+
geom_bar(stat='identity')+
labs(x = "Category")
ggplotly(g)
An another option will be to set arguments in ggplot
to be use in the tooltip
argument of ggplotly
such as:
g=df %>%
ggplot(aes(x=reorder(category, n), y=n, fill=subCategory,
text = paste("category:", category), text2 = n, text3 = subCategory))+
geom_bar(stat='identity')+
labs(x = "Category")
ggplotly(g, tooltip = c("text","text2","text3"))
Does it answer your question ?
Edit labels in tooltip for plotly maps using ggplot2 in r
I am new to plotly too but have come across a similar problem for my ggplot2 bubble plots when using ggplotly()
. I have finally found a solution that works for me and thought it might help you, too, although I haven't tried it for choropleth maps.
Your first question was to customize the tooltip so it displays some of the variables in the dataset (including those not mapped to aesthetics).
In your UPDATE#3 you introduce:text = paste("Province:", NAME_1)
into your aes. If you want to add a second line of custom variables or text, just keep adding it into the brackets:text = paste("Province:", NAME_1, "Example III:", example1)
To add a line break between both add <br>
in the spot where you want the break to be, like:text = paste("Province:", NAME_1, "<br>", "Example III:", example1)
Your second question was to customize the tooltip so it does NOT display other (default) variables (that are mapped to aesthetics, such as the coordinates).
I found this very easy addition to the ggplotly()
function that did the trick for me: ggplotly(gg, tooltip = c("text"))
In my case, this removed ALL default variables that are shown in the tooltip and only showed those that are custom specified with text
above. You can add other variables back in by doing ggplotly(gg, tooltip = c("text","x"))
The order of the variables shown in the tooltip will be the same as the order specified in the tooltip
argument. I found this documented here: https://github.com/ropensci/plotly/blob/master/R/ggplotly.R
This solution worked (in principle) for me using R 3.1.1 and plotly 3.4.13
Showing a list of corresponding labels for ggplotly hover
Aggregate the indicator by concatenation.
dataNew <- data %>%
group_by(GeoAreaName, cat) %>%
summarize(Indicator = paste(Indicator, collapse=", "), count=n())
Plotting:
p <- ggplot(data = dataNew, aes(x = GeoAreaName, y=count, fill= cat, text= Indicator)) +
geom_bar(stat="identity")
Set tooltip text for plot with more than one aes()
Because you sent me the comment on your last question I looked at this from both perspectives. I kept getting errors with this code. Instead of focusing on resolving those issues, I'm going to show you how to customize the tooltips without first having created a ggplotly
object and when you have already (like in your last question).
- Starting from a
ggplot
object - Starting from a
ggplotly
orplotly
object
1)
Since you are simply modifying tooltips that still represent the x- and y-axes, I think this is the easiest approach. I used stringr
from within tidyverse
to modify the tooltips.
library(tidyverse)
# create plotly object to modify
p2 <- plotly_build(p)
# now modify the text calls for each trace that this applies to
# modfiy existing tooltips
# this is the first trace (the bar chart or first geom in ggplot object)
p2$x$data[[1]]$text <- str_replace_all(p2$x$data[[1]]$text,
"year2", "Year ") %>%
str_replace_all(., fixed("pta_count/(max(pta_count)/max(scope_ntis_ciu))"),
"Count of issues ")
# validate change
p2$x$data[[1]]$text # looks right
# now for the second trace
p2$x$data[[2]]$text <- str_replace_all(
p2$x$data[[2]]$text, "year2", "Year ") %>%
str_replace_all(., "scope_ntis_mean", "Count of issues ")
# validate change
p2$x$data[[2]]$text # looks right
2)
First I added hoverinfo = "skip"
to the invisible trace. Then I assigned the build of that ggplotly
object to an object name. Please keep in mind this is using the version of the object p
from your previous question.
p2 <- ggplotly(p) %>%
add_trace(inherit = F, x = ~year2,
y = ~(pta_count/(max(pta_count)/ max(scope_ntis_ciu))
) * (max(dt2$pta_count)/max(dt2$scope_ntis_ciu)),
data = dt2,
yaxis = "y2",
hoverinfo = "skip", # NO TOOLTIPS!
alpha = 0, # make it invisible
type = "bar") %>%
layout(margin = list(l = 85, r = 85),
yaxis2 = list(
ticklen = 3.7, # to match other axes
tickcolor = "rgba(51, 51, 51, 1)", # to match other axes
tickfont = list(size = 11.7, # to match other axes
color = "rgba(77, 77, 77, 1)"), # to match the others
titlefont = list(size = 11.7), # to match other axes
side = "right",
overlaying = "y",
showgrid = F, # to match ggplot version
dtick = 25, # between ticks
title = "PTA Count\n(green columns indicate number of PTAs\n signed in given 5-year interval)"))
p2$x$data[[1]]$text <- str_replace_all(
p2$x$data[[1]]$text, "year2", "Year ") %>%
str_replace_all(., fixed("pta_count/(max(pta_count)/max(scope_ntis_ciu))"),
"Count of issues ")
# validate
p2$x$data[[1]]$text
# now for the second trace
p2$x$data[[2]]$text <- str_replace_all(
p2$x$data[[2]]$text, "year2", "Year ") %>%
str_replace_all(., "scope_ntis_mean", "Count of issues ")
# validate
p2$x$data[[2]]$text
Essentially, plotly_build
and ggplotly
create the same object. In both 1 and 2, p2
is ready to be called.
Related Topics
How to Work with Large Numbers in R
Replacing Numbers Within a Range with a Factor
How to Read Only Lines That Fulfil a Condition from a CSV into R
Proper Idiom for Adding Zero Count Rows in Tidyr/Dplyr
Append Value to Empty Vector in R
Getting Strings Recognized as Variable Names in R
Reading Multiple Files and Calculating Mean Based on User Input
Grouped Barplot in R with Error Bars
Non-Equi Join Using Data.Table: Column Missing from the Output
Using Lists Inside Data.Table Columns
How to Update R Packages in Default Library on Windows 7
Error ".Onload Failed in Loadnamespace() for 'Tcltk'"
Mean of Each Element of a List of Matrices
Converting Two Columns of a Data Frame to a Named Vector
Is Set.Seed Consistent Over Different Versions of R (And Ubuntu)
Assign Intermediate Output to Temp Variable as Part of Dplyr Pipeline
How to Install Development Version of R Packages Github Repository
How to Use Spread on Multiple Columns in Tidyr Similar to Dcast