Retrieve axis tick information from a plotly figure - r

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.

Related

Is there a way to create a kissing people curve using ggplot2 in R

Is it possible to create custom graphs using ggplot2, for example I want to create a graph of kissing people.
Simple variant
Not completely, but partially, I was able to reproduce it, everything except for the "lines of the eyes" is not clear how to mark them
But how to make a more complex graph of kissing people. In general, is it possible to somehow approximate such a curve, more voluminou?
thank you for your help.
perhaps not what you are looking for, but if you have already got the image, and want to reproduce it in ggplot, then you can use the following method:
library(tidyverse)
library(magick)
library(terra)
# read image
im <- image_read("./data/kiss_1.png")
# conver to black/white image
im2 <- im %>%
image_quantize(
max = 2,
colorspace = "gray" )
# get a matrix of the pixel-colors
m <- as.raster(im2) %>% as.matrix()
# extract coordinates of the black pixels
df <- as.data.frame(which(m == "#000000ff", arr.ind=TRUE))
df$row <- df$row * -1
# plot point
ggplot(df, aes(x = col, y = row)) + geom_point()

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
)

Suppress default text in tooltip using plot_ly

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?

ggvis slider for bar plots

Am using R version 3.2.2. I am trying to create a bar plot with date on the x axis with a slider to control the number of date values displayed. I cannot figure what option helps me do this. I tried:
library(dplyr)
library(ggvis)
library(shiny)
shinyServer(function(input,output){
final_data %>%
ggvis(~Date, ~work_left) %>%
layer_bars(width = input_slider(min = 1, max = 10)) %>%
along with a host of other options including size which I found on other help sites. But none of them work.
My ui.r is a simple display of the chart in the main panel.
Any help is appreciated. Thanks

Resources