Search code examples
rggvis

Is it possible to plot a cartesian coordinate system with ggvis?


the topic says it all. Just want to know/figure out how I can plot an interactive cartesian coordinate system (the origin of both axes is in the center) with ggvis.

Is that possible? Google didnt help... Here is a short example:

library(ggvis)
library(magrittr)

x = -5:5
y = -5:5
data = data.frame("x"=x,"y"=y)
plot = data %>% ggvis(~x,~y) 
plot

EDIT: Ok, I figured something out:

plot = data %>% ggvis(~x,~y) %>% add_axis("x",offset=-250, grid=NA) %>% add_axis("y",offset=-250,grid=NA)

With the property offset I can "offset" the axis. But they are not fixed. If I resize the viewer window, they move of course...


Solution

  • One solution (a bit of a hack) is to draw the lines using layer_paths()

    data_line <- data.frame(
      x_rng = c(-5, 5), 
      y_rng = c(0, 0)
    )  
    
    data_line2 <- data.frame(
      x_rng = c(0, 0), 
      y_rng = c(-5, 5)
    )  
    
    data %>% ggvis(~x, ~y) %>%
      layer_paths(
        x = ~x_rng, 
        y = ~y_rng,
        stroke := "black", 
        data = data_line
      ) %>%
      layer_paths(
        x = ~x_rng, 
        y = ~y_rng,
        stroke := "black", 
        data = data_line2
      ) %>%
      layer_points()