Retrieve axis tick information from a plotly figur

2019-08-15 01:55发布

问题:

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?

回答1:

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()


回答2:

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.