繁体   English   中英

更改R Shiny / ggvis图中的标签

[英]Change labels in R shiny/ggvis plot

我需要使ggvislabels = axis功能发光

在R中, labels axis参数允许更改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))

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

在此处输入图片说明

现在,我们尝试使用ggvis在Shiny上获得完全相同的效果:

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)

在此处输入图片说明

当我们用红色突出显示时,距离不正确。 那么我们如何才能在光泽上与在普通R上具有axis(label = ...

好的,我在弄弄它,您必须先将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)

更新的输出

输出量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM