更改R shiny / ggvis图中的标签

时间:2015-08-25 15:53:44

标签: r shiny ggvis

我需要在闪亮 labels = 轴功能中使用 ggvis

在R中,标签轴参数允许更改x标签(添加Kb格式),保持顺序和项目之间的相对距离:

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))

有了这个,我们得到了我们需要的东西:

enter image description here

现在我们尝试使用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

当我们以红色突出显示时,距离不正确。那么我们如何才能在平面R上用轴(标签= ...

1 个答案:

答案 0 :(得分:3)

好的,我摆弄它,你必须首先将你的x轴转换为factor。我已经为dataframe添加了一些排序,因为您可能也希望它们按顺序排列(否则您可以轻松删除它)。您可以自己在轴上放置标签。如果您有任何疑问,请告诉我。此外,我更改了x轴上的数据以显示mtcars$disp,因为它具有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)

更新输出

Output