1
votes

I need to have with ggvis in shiny the labels= axis feature.

In R the labels axis argument allow to change the x labels (adding a Kb format), that keep the order and the relative distance between items:

mtcars <- mtcars[1:10, ]
my_data <- mtcars[order(mtcars$disp),]
xpos <- sort(mtcars$disp)
plot(my_data$disp, my_data$mpg, type = "l", xaxt="n")
axis(1, at=xpos, labels=sprintf("%.2fKb", xpos/10))

With this we get what we need:

enter image description here

Now we try to get the exact same on shiny with ggvis:

library(shiny)
library(ggvis)
mtcars
ui <- pageWithSidebar( div(),
                       sidebarPanel(uiOutput("plot_ui"),width=2),
                                    mainPanel(ggvisOutput("plot"))
)

server <- function(input, output, session) {
    mtc <- reactive({
        my_data <- mtcars[1:10, ]
        # Do some sorting/ordering if you want (here sorted by disp)
        my_data <- my_data[order(my_data$disp), ]
        my_labels <- c(as.character(paste0((my_data$disp)/1000, "Kb")))
        y <- my_data$mpg
        x <- factor(c(my_data$disp), labels = c(unique(my_labels)))
        data.frame(x = x, y = y)
    })

   mtc %>%
   ggvis(~x,~y ) %>%
   layer_lines() %>%
   add_axis("x", properties=axis_props(labels=list(fontSize = 10))) %>%
   bind_shiny("plot", "plot_ui")
}

shinyApp(ui = ui, server = server)

enter image description here

As we highlight in red, the distances are not correct. So how can we have on shiny the same plot we have on plain R with axis(label=... ?

1
Why do you use ggvis instead of plot in your observer? Is this question related to axis in ggvis? - Stereo
Yes it's probably a ggvis axis question, I updated tags - user3313834

1 Answers

3
votes

Ok, I fiddled around with it and you have to convert your x-axis into a factor first. I've added some sorting to the dataframe as you probably want these to be in order also (you can easily remove it otherwise). You can put labels on the axis yourself. Let me know if you have any questions. Also I changed the data on the x-axis to display mtcars$disp as it has values in 100s

rm(list = ls())
library(shiny)
library(ggvis)
mtcars
ui <- pageWithSidebar(
  div(),
  sidebarPanel(
    sliderInput("n", "Number of points", min = 1, max = nrow(mtcars),value = 10, step = 1),
    uiOutput("plot_ui"),width=2),
  mainPanel(ggvisOutput("plot"))
)

server <- function(input, output, session) {
  mtc <- reactive({ 
    my_data <- mtcars[1:input$n, ] 
    # Do some sorting/ordering if you want (here sorted by disp)
    my_data <- my_data[order(my_data$disp),]
    my_labels <- c(as.character(paste0((my_data$disp)/1000,"Kb")))
    y <- my_data$mpg
    x <- factor(c(my_data$disp), labels=c(unique(my_labels)))
    data.frame(x = x, y = y)
  })

  mtc %>%
    ggvis(~x,~y ) %>%
    layer_lines() %>%
    add_axis("x", properties=axis_props(labels=list(fontSize = 10))) %>%
    bind_shiny("plot", "plot_ui")
}

shinyApp(ui = ui, server = server)

Updated Output

Output