Search code examples
rplotplotly

Make dotted gridlines with plotly


Reading the documentation of plotly I thought I can use griddash to style the gridlines such that the line is not solid but dotted (say).

However, this does not work (gridcolor and gridwidth do work and are here just for better visibility):

library(plotly)

d <- data.frame(x = LETTERS[1:3], y = c(13, 50, 97))

plot_ly(d) %>%
  add_trace(x = ~ x, y = ~ y, type = "bar") %>%
  layout(yaxis = list(griddash = "dot", gridwidth = 2, gridcolor = "red"))

Barplot with red thicker gridlines which are however solid and not dottes as intended


Manually adding stroke-dasharray would do the trick:

Barchart with a dotted gridline and the Chrome developer console which shows the manually added stroke-dasharray attribute for the corresponding gridline

Which makes me believe that this is a bug and shoudl be filed as such?


Solution

  • The reason this argument (and several others) isn't working is due to the Plotly JS dependency. Right now the R package appears to still be using 2.11.1. Meanwhile, Plotly JS is on 2.22? 2.23?

    If you want to be able to use this argument, this is one way you can make plotly work for you-- change the dependency.

    BTW, I used 2.21 here, because I already use this chunk regularly. You can always capture the dependency URL for a newer version.

    library(htmltools)
    library(plotly)
    
    #----------- your code ------------
    d <- data.frame(x = LETTERS[1:3], y = c(13, 50, 97))
    
    plot_ly(d) %>%
      add_trace(x = ~ x, y = ~ y, type = "bar") %>%
      layout(yaxis = list(griddash = "dot", gridwidth = 2, gridcolor = "red"))
    
    #----------- added code -------------
    
    # assign plot to object
    plt <- plotly::last_plot()   # !! function exists in multiple libraries
    
    # create new Plotly JS dependency
    newDep <- htmlDependency(name = "plotly-latest", 
                             version = "2.21.1",     
                             src = list(href = "https://cdn.plot.ly"),
                             script = "plotly-2.21.0.min.js")
    
    # add that dependency to plot
    plt$dependencies[[6]] <- newDep
    
    # see what you've got
    plt
    

    enter image description here