5

I am using ggplot2 and the plotly R packages to generate a volcano plot to visualize protein differential abundance data.

library(ggplot2)
library(plotly)

nVals <- 80
nFacets <- 2

#example dataset
proteins <- rep(paste0('protein_', c(1:(nVals / nFacets))), nFacets)
set.seed(1)
dat <- data.frame(log_FC = c(rnorm(nVals*0.8, 0, 1), rnorm(nVals*0.2, 0, 12)),
                  log_Pval = abs(rnorm(nVals, mean=0, sd=0.01)),
                  facet = rep(paste0('Cell line ', 1:nFacets), nVals / nFacets),
                  protein = proteins[order(proteins)])


#make ggplot2 object
p <- ggplot(dat, aes(y = log_Pval, x = log_FC, text = protein)) +
  facet_wrap(~ facet) +
  geom_point()

#convert p to plotly object with plotly::ggplotly
ggplotly(p)

Example of current output

I am using the tooltip feature in plotly to show the data associated with each point. I would like to extend the tooltip feature to highlight the same protein in different facets of the plot.

In other words, when a cursor hovers over a point in 1 facet, the tooltip box would show up on all points which have the same value in the dat$protein column in adjacent facets.

Here is an example of what I am aiming for.

Is there some way of the customizing the behavior of the tooltip to achieve the what I have described?

aaronj
  • 53
  • 5

1 Answers1

2

With crosstalk, you can have widgets communicate with each other. Create a SharedData object from your data frame, and select protein as the key.

library(crosstalk)
shared_df <- SharedData$new(dat, key = ~protein)

Then, use shared_df instead of dat with ggplot. If you select a point in one plot, it will highlight the matching data point (by protein) in the second plot. Please let me know if this meets your needs.

Ben
  • 28,684
  • 5
  • 23
  • 45
  • 2
    This defiantly solves the problem and allows me to compare points between facets. I'd really like the tooltip to show up on the other point though. However, after doing some more research I don't think that is possible without using javascript. – aaronj May 25 '19 at 22:49
  • 1
    Anyone figure out how to get the tooltip to show up on the other point? – dca Apr 12 '22 at 16:24