Search code examples
rgraphplotlyaxis-labelsr-plotly

Plotly: How to set a minimum value on secondary y-axis?


I want to set a minimum value on the secondary y-axis. This is my code :

library(plotly)

# my data
value <- c(300000,400000,500000,600000,500000,600000)
x1 <- c(3,4,5,5,4,3)
x2 <-c(3,4,5,5,4,3)
name <- c("martin","john","marc","igor","thea","julia")
df <- data.frame(value, x1, x2, name)


# graph with plotly
graph=df %>% 
  plot_ly(x = ~name) %>% 
  add_bars(y = ~x1,
           name = "bar1") %>% 
  add_bars(y = ~x2,
           name = "bar2") %>%
  add_lines(y = ~value,
            name = "line",
            yaxis = "y2") %>% 
  layout(barmode = "bar",
         yaxis2 = list(overlaying = "y",
                       side = "right"),
         barmode = "bar",
         legend = list(x = 1.1, y =1))

# showing graph
  graph

and i get this : enter image description here

but i want the secondary y-axis start at 200k (or 100k) instead of 300k.

How can we fix it ? Some help would be appreciated


Solution

  • Generally, if you've already got a fig set up:

    fig <- fig %>% layout(yaxis2 = list(range = c(<min>, <max>)))
    

    And in your specific case:

    graph <- graph %>% layout(yaxis2 = list(range = c(200000,600000)))
    

    Plot

    enter image description here

    Complete code:

    library(plotly)
    
    # my data
    value <- c(300000,400000,500000,600000,500000,600000)
    x1 <- c(3,4,5,5,4,3)
    x2 <-c(3,4,5,5,4,3)
    name <- c("martin","john","marc","igor","thea","julia")
    df <- data.frame(value, x1, x2, name)
    
    
    # graph with plotly
    graph=df %>% 
      plot_ly(x = ~name) %>% 
      add_bars(y = ~x1,
               name = "bar1") %>% 
      add_bars(y = ~x2,
               name = "bar2") %>%
      add_lines(y = ~value,
                name = "line",
                yaxis = "y2") %>% 
      layout(barmode = "bar",
             yaxis2 = list(overlaying = "y",
                           side = "right"),
             barmode = "bar",
             legend = list(x = 1.1, y =1))
    
    # showing graph
    #graph
    
    graph <- graph %>% layout(yaxis2 = list(
          #scaleanchor = "x",
          #scaleratio = 0.2,
          range = c(200000,600000)
          #title = "1:5"
          ))
    graph