Home > Software engineering >  Is there any way to add axis lines to a graph with Plotly in R?
Is there any way to add axis lines to a graph with Plotly in R?

Time:01-20

I'm currently making graphs with Plotly for publication, and I'm trying to display the axis lines, which I would expect is an easy and basic thing to do in a plot.

Take this dummy graph :

if (!require("plotly")) install.packages("plotly")
library(plotly)

group <- c("a", "b", "c")
values <- c(0, 5, 10)
df <- data.frame(group, values)
plot <- df %>% 
  plot_ly() %>% 
  add_trace(x = ~group, y = ~values, type = "scatter", mode = "line") %>% 
  layout(yaxis = list(ticks = "outside"), xaxis = list(zeroline = TRUE))
plot

Dummy plot

I'm trying to add a vertical y-axis line that would interact with the ticks nicely. I thought that enabling a zero line with zeroline = TRUE in the xaxis call would work but it doesn't produce the "zeroline" because the data is categorical and there's no zero. The inside and outside options of the ticks call move around an invisible axis so that "zero" value must exist somehow.

Moving on, I then tried this vertical line function found on the web (there's an equivalent for horizontal lines) :

vline <- function(x = 0) {
  list(
    type = "line", 
    y0 = 0, 
    y1 = 1, 
    yref = "paper",
    x0 = x, 
    x1 = x, 
    line = list(color = "black", width = 1)
  )
}

Dummy plot with vline

It works, but it's clunky for multiple reasons :

  1. When manually resizing the Viewer, the line behaves differently than the rest of the graph and doesn't stick to the axis ticks,
  2. It goes a bit too low to be pretty,
  3. The placement has to be fine-tuned manually, and (cf. point 1) has to be adapted each time the plot is resized,
  4. It's a generally inelegant solution to something I thought would be straightforward.

Note that in my dummy example, there is a datapoint at 0. If there isn't one, then the x-axis zero line is gone too, which is another problem I have. But I suppose fixing one will fix the other.

I found nothing on the Plotly reference that would resemble a solution to this problem. Any pointers ?

CodePudding user response:

I guess you are looking for showline as can be seen enter image description here

  • Related