Dan Dan - 3 months ago 30
R Question

common axis subplots with plot.ly for R

I am attempting to use subplots with the

plot.ly
R library for interactive online charting. I can successfully create a subplot, however am struggling to only have a single y-axis that is common to both charts.

The
plot.ly
website does provide an example for a common x-axis, however this is done slightly differently using and additional
trace
rather than the
group
option that is provided within the
plot_ly()
function.

example code:

library(data.table)
library(plotly)
dt <- data.table(x = c("A","B","C","D","A","B","C","D"),
y = c(12,4,3,9,5,10,3,7),
group = factor(c(rep("G1",4),rep("G2",4))))
dt$id <- as.integer(dt$group)
xx <- xaxis_standard
yy <- yaxis_standard
p <- plot_ly(dt, x=x, y=y, group = group, xaxis = paste0("x",id))
p <- layout(p, yaxis = list(range = c(0, max(y))))
p <- subplot(p, margin = 0.05)
p <- layout(p,showlegend = F, yaxis = list(anchor = 'x1'))
p


This image shows what results when I execute the code.
Plot.ly subplot chart

What I would like to have is the same chart, however without the y-axis on the right hand subplot.

Answer

Subplots are on separate axes labeled xaxis2, yaxis2, etc. Those axes are also arguments to layout().

p <- layout(p, showlegend = F, yaxis = list(anchor = 'x1'), 
            yaxis2 = list(showticklabels = F))
p

enter image description here