ACE
ACE

Reputation: 327

Change y limits in subplot plotly

I am using the plotly library to plot a series of graphs that share a common x-axis. An example is shown in the documentation under the scaled subplot function - https://plotly.com/r/subplots/

Is there a way to change the y limits for each individual plots? Here is what I have as an example

library(plotly)

data <- data.frame("Time" = 1:100, "y1" = rnorm(100), "y2" = rnorm(100))

df <- data %>% 
  tidyr::gather(variable, value, -Time) %>%
  transform(id = as.integer(factor(variable))) 

 df$variable <- factor( df$variable, levels = unique( df$variable))

  p <- plot_ly(data = df,x = ~Time, y = ~value, color = ~variable, colors = "Dark2",
          yaxis = ~paste0( "y",sort(id, decreasing = F))
          ) %>%
    add_lines() %>% 
    plotly::subplot(nrows = length(unique(df$variable)), shareX = TRUE)
  
  p

In the above code, how do I change the yaxis limits of y2 from -10 to 10?

Upvotes: 1

Views: 1388

Answers (1)

tamtam
tamtam

Reputation: 3671

You can just add a layout-layer and define the yaxis of the second plot with the yaxis2 argument.

data <- data.frame("Time" = 1:100, "y1" = rnorm(100), "y2" = rnorm(100))

df <- data %>% 
  tidyr::gather(variable, value, -Time) %>%
  transform(id = as.integer(factor(variable))) 

df$variable <- factor( df$variable, levels = unique( df$variable))

p <- plot_ly(data = df,x = ~Time, y = ~value, color = ~variable, colors = "Dark2",
             yaxis = ~paste0( "y",sort(id, decreasing = F))
) %>%
  add_lines() %>% 
  plotly::subplot(nrows = length(unique(df$variable)), shareX = TRUE)

p %>%
  layout(yaxis2 = list(range = c(-10,10)))

enter image description here

Upvotes: 2

Related Questions