Search code examples
rgraphscaleggvis

ggvis: x-axis with whole number scale


I want to get whole numbers for x-axis for ggvis plot.

MWE

df <- 
  structure(list(Factor = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
  2L, 3L, 1L, 2L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
  X = c(15.5133333333333, 14.63, 14.41, 14.1266666666667, 13.1833333333333, 
  12.9466666666667, 13.6133333333333, 13.55, 13.5333333333333, 
  11.5566666666667, 11.3066666666667, 11.4566666666667), Y = c(20L, 
  20L, 20L, 40L, 40L, 40L, 70L, 70L, 70L, 100L, 100L, 100L)), .Names = c("Factor", 
  "X", "Y"), row.names = c(NA, -12L), class = "data.frame")

library(ggvis)

ggvis(data=df
      , x= ~X
      , y= ~Y
      , fill= ~Factor
      , stroke = ~Factor) %>% 
  arrange(Y) %>%
  group_by(Factor) %>%
  layer_points(shape=~Factor) %>% 
  layer_paths(fill := NA)  %>%
  add_axis('x', orient=c('bottom'), format='####') 

enter image description here

One possibility is use values=seq(from=10, to=16, by=1) in add_axis(). But this is approach is not automated.


Solution

  • Setting the format argument to 'd' will display only integer values in the axis label:

    library(ggvis)
    library(dplyr)
    ##
    ggvis(data=df
          , x= ~X
          , y= ~Y
          , fill= ~Factor
          , stroke = ~Factor) %>% 
      arrange(Y) %>%
      group_by(Factor) %>%
      layer_points(shape=~Factor) %>% 
      layer_paths(fill := NA)  %>%
      add_axis('x', orient=c('bottom'), format='d')
    

    enter image description here

    More information on d3 formatting specifications is available on this page, as mentioned in the Common Properties section of this ggvis guide.