Suppress default text in tooltip using plot_ly - r

With plot_ly(), I am able to add what I want in the tool tip, but I don't manage to get rid of the default value. Is there way to do this ?
In the example below, for the first point, the tooltip is "250 company1". I would like to get only "company1". I have a solution using ggplot2 and then ggplotly() with the tooltip option, but I would rather remain with plotly only.
require(plotly)
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)
plot_ly(data=d,x=seq,y=value,text=name)

You need the hoverinfo parameter for plot_ly:
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)
plot_ly(data=d,x=seq,y=value,text=name,hoverinfo="text")
More reading: plotly R chart attribute reference

Gopala, I asked a similar question and found the answer useful. Perhaps it will help you too.
How can I remove the size line in the hoverinfo of a Plotly chart in R?

Related

Animating Histograms with plotly

I'm trying to create an animated demonstration of the Law of Large Numbers, where I want to show the histogram converging to the density as the sample size increase.
I can do this with R shiny, putting a slider on the sample size, but when I try to set up a plotly animation using the sample size as the frame, I get an error deep in the bowels of ggploty. Here is the sample code:
library(tidyverse)
library(plotly)
XXX <- rnorm(200)
plotdat <- bind_rows(lapply(25:200, function(i) data.frame(x=XXX[1:i],f=i)))
hplot <- ggplot(plotdat,aes(x,frame=f)) + geom_histogram(binwidth=.25)
ggplotly(hplot)
The last line returns the error. Error in -data$group : invalid argument to unary operator.
I'm not sure where it is suppose to be getting data$group (this value has been magically set for me in other invocations of ggplotly).
Skipping the initial ggplot and going straight to plotly, does this work for you?
plotdat %>%
plot_ly(x=~x,
type = 'histogram',
frame = ~f) %>%
layout(yaxis = list(range = c(0,50)))
Or, using your original syntax, we can add a position specification that seems to prevent the bug. This version looks better, with standard ggplot formatting and tweened animation.
hplot <- ggplot(plotdat, aes(x, frame = f)) +
geom_histogram(binwidth=.25, position = "identity")
ggplotly(hplot) %>%
animation_opts(frame = 100) # minimum ms per frame to control speed
(I don't know why this fixes it, but when I googled your error I saw a plotly issue on github that was solved by specifying the position, and it seems to fix the error here too. https://github.com/plotly/plotly.R/issues/1544)

Is there a way to have a highlighted chart as well as have interactivity of selecting elements in R?

I have come across a beautiful chart on this webpage: https://ourworldindata.org/coronavirus and interested to know if we can build the same chart in R with functionality of having highlighted series as well as selecting any line on hovering ?
I have build static highlighted charts using gghighlight but those are not interactive.
Plotly can help in interaction but I think they don't work with gghighlight.
So how can we have the combination of both highlight and interactivity in charts as in the link shared on top ?
Is it possible to achieve same results in R ? It would be really helpful if someone could share an example or link that can help.
(UPDATE: May be I can manually highlight lines by creating a factor column instead of using gghighlight and then pass it to ggplotly but then can ggplotly or some other library provide similar results on hover ?)
(NOTE: Not looking for animation. Just need highlighted, hover over interactive chart)
Below is the snapshot of same chart hovered over US (This chart is also similar to the one shared in World Economic Forum many times.)
Using plotly you can use highlight() to achive this.
This is a slightly modified example from here:
library(plotly)
# load the `txhousing` dataset
data(txhousing, package = "ggplot2")
# declare `city` as the SQL 'query by' column
tx <- highlight_key(txhousing, ~city)
# initiate a plotly object
base <- plot_ly(tx, color = I("black")) %>%
group_by(city)
# create a time series of median house price
time_series <- base %>%
group_by(city) %>%
add_lines(x = ~date, y = ~median)
highlight(
time_series,
on = "plotly_hover",
selectize = FALSE,
dynamic = FALSE,
color = "red",
persistent = FALSE
)

Retrieve axis tick information from a plotly figure

I'm plotting a heatmap using R plotly:
set.seed(1)
df <- reshape2::melt(matrix(rnorm(100*20),100,20,dimnames = list(paste0("G",1:100),paste0("S",1:20))))
library(plotly)
library(dplyr)
plot_ly(z=c(df$value),x=df$Var2,y=df$Var1,colors=grDevices::colorRamp(c("darkblue","gray","darkred")),type="heatmap",colorbar=list(title="Scaled Value",len=0.4)) %>%
layout(yaxis=list(title=NULL),xaxis=list(tickangle=90,tickvals=10,ticktext="X-Label"))
As you can see, plotly is not showing all y-axis ticks. My question is whether it is possible, and if so how, to retrieve the y-axis tick labels plotly selected to show?
I saved the plot object:
plotly.obj <- plot_ly(z=c(df$value),x=df$Var2,y=df$Var1,colors=grDevices::colorRamp(c("darkblue","gray","darkred")),type="heatmap",colorbar=list(title="Scaled Value",len=0.4)) %>%
layout(yaxis=list(title=NULL),xaxis=list(tickangle=90,tickvals=10,ticktext="X-Label"))
And looked around and it seems that perhaps plotly.obj$x$layoutAttrs should store this information but it doesn't:
> plotly.obj$x$layoutAttrs
$`102ce55fd393e`
$`102ce55fd393e`$yaxis
$`102ce55fd393e`$yaxis$title
NULL
$`102ce55fd393e`$xaxis
$`102ce55fd393e`$xaxis$tickangle
[1] 90
$`102ce55fd393e`$xaxis$tickvals
[1] 10
$`102ce55fd393e`$xaxis$ticktext
[1] "X-Label"
Any idea?
I don't think you can get the ticks, that are finally rendered. But you can get all the levels of the y-axis, that ploty can choose from.
levels(plotly.obj$x$attrs$`2c4c148651ae`$y)
The ticks that are finally rendered are dynamically chosen and will adapt, depending on your plot size etc.
You can also check out the attributes with plotly_json():
plot_ly(z=c(df$value),x=df$Var2,y=df$Var1,colors=grDevices::colorRamp(c("darkblue","gray","darkred")),type="heatmap",colorbar=list(title="Scaled Value",len=0.4)) %>%
layout(yaxis=list(title=NULL),xaxis=list(tickangle=90,tickvals=10,ticktext="X-Label")) %>%
plotly_json()
I got the answer from a github issue I posted on ropensci/plotly:
set.seed(1)
df <- reshape2::melt(matrix(rnorm(100*20),100,20,dimnames = list(paste0("G",1:100),paste0("S",1:20))))
library(plotly)
library(dplyr)
plot_ly(z=c(df$value),x=df$Var2,y=df$Var1,colors=grDevices::colorRamp(c("darkblue","gray","darkred")),type="heatmap",colorbar=list(title="Scaled Value",len=0.4)) %>%
layout(yaxis=list(title=NULL),xaxis=list(tickangle=90,tickvals=10,ticktext="X-Label")) %>%
htmlwidgets::onRender(
"function(el, x) {
alert(el._fullLayout.yaxis._vals.map(function(i) { return i.text; }));
}"
)
Will pop up a browser window with the tick labels.
The question now is if this can be saved/piped to an R variable or written to a file so it can be done automatically rather than interactively. That's going to be another post.

R: Change strip text of effect plot

I have a simple effect plot in R using the effects package. Here is an example:
require(effects)
A <- rnorm(100)
B <- rnorm(100)
C <- factor(rep(c("right", "left"), 50))
eff <- effect("B:C", lm(A~B*C))
plot(eff)
I want to change the strip text of the panels (in this case C:left and C:right) to any text (eg. text:left). There is an unelegant way to achieve this by changing the data using:
names(eff$x)[names(eff$x)=="C"] <- "text"
I don't want to change the data though. Also changing the element name restricts me from using spaces or other special symbols. Using the function to change the strip names in plot.eff
plot(..., strip = function(...) strip.default(..., strip.names = c(factor.names, TRUE)))
gives me an error though ("formal argument "strip" matched by multiple actual arguments") since this seems to be used by the xyplot too.
Is there a way to change the strip text without modifying the data? Any help would be highly appreciated!

Add a vertical line to a line chart from the googleVis

What I would like to do is add a vertical line to a line chart in R from the googleVis package. Does anyone know if this is supported? For example, given the following simple line chart, I would like to add a vertical line at x=2. Is this even possible?
# Simple example. Must bring in 'googleVis' package first.
df <- data.frame(country=c(1,2,3), val1=c(1,3,4), val2=c(23,12,32))
Line1 <- gvisLineChart(df, xvar="country", yvar=c("val1", "val2"))
plot(Line1)
I realized how to do it by asking the developer. You use NAs to get a vertical reference line like this:
library(googleVis)
dat <- data.frame(x=c(2,2,1,3,4),
y1=c(0,3,NA,NA,NA),
y2=c(NA,NA,0,3,2))
plot(gvisScatterChart(dat,
options=list(lineWidth=2,
pointSize=2))
)

Resources