【问题标题】:In R shiny is there a way to freeze the x-axis on an interactive plot?在 R 中,有没有办法在交互式绘图上冻结 x 轴?
【发布时间】:2020-07-22 13:56:34
【问题描述】:

我正在使用 R Shiny 中的 ggplot 创建交互式折线图。我这样做的方式是让用户在 UI 中使用选择器输入选择他们想要在图中看到的值。然后在服务器中根据用户的选择过滤数据。我使用scale_x_continuous 在ggplot 中指定了x 轴。我将序列设置为 0 到 24 之间的间隔为 1。但是,当用户选择 1-10 时,x 轴将更改为仅显示 1-10。

无论用户选择什么,我都希望 x 轴保持 0 到 24。有没有办法做到这一点?解决方案是否会以不同的方式限制指定ggplot x 轴限制,或者我如何使用选择器输入来过滤数据?

谢谢!

如果有帮助,这是我的代码:

library(shiny)
library(tidyverse)
library(shinyWidgets)

# Create sample dataset and name bin
set.seed(1234) 
hour <- sample(1:24, size=100, replace=TRUE)
calls <- sample(1:55, size=100, replace =TRUE)
mydata <- data.frame(hour,calls)
name <- mydata %>% 
  group_by(hour) %>% 
  summarize(n())

name_bin <- as.data.frame(name$hour)

ui <- fluidPage(
  h1 ("R shiny ggplot Question"),
  pickerInput(
    inputId = "myPicker",
    label = "Select Hour in the day",  
    choices = name_bin, 
    options = list(
      `actions-box` = TRUE,
      size = 10, 
      `selected-text-format` = "count > 3"),
    multiple = TRUE),
  box(
    width = 11,
    plotOutput("graph1"))
)

server <- function(input,output,session) {

output$graph1 <- renderPlot({

  g1 <- dplyr::filter(mydata,hour %in% input$myPicker) 

  g2 <- g1 %>% 
    group_by(hour) %>% 
    summarize(number = n())

  ggplot(g2, aes(x=hour, y=number)) + 
    geom_line(color = 'darkblue') + geom_point() +
    scale_x_continuous(breaks = seq(0,24, by=1)) +  ###### Better way to set x-limits?
    scale_y_continuous(breaks = seq(0, max(g2$number), by=5))+ 
    theme_minimal()+
    labs(y="Number of Calls", x="Hour in the day",title = "")
})
}

shinyApp(ui, server)

【问题讨论】:

    标签: r ggplot2 shiny


    【解决方案1】:

    有几种方法可以设置轴的限制:你快到了!

    在您的renderPlot() 函数中调用scale_x_continuous 仅设置轴中的中断(它的标记方式)。您想要设置限制,您可以在 scale_x_continuous 函数中通过参数 limits= 进行设置。 See the documentation for more information,但这应该适合你:

    scale_x_continuous(breaks = seq(0,24, by=1), limits = c(0,24))
    

    或者,如果您只想设置限制,但轴中的默认“中断”很好,您可以使用 xlim(0,24) 代替 scale_x_continuous 更轻松地访问 x 和 y 限制。

    但请注意:设置轴的限制将导致删除该数据 - 这意味着它不会用于任何进一步的统计功能。如果您仍需要为绘图中的其他统计功能保留该数据,您可以使用coord_cartesian()(请参阅the documentation here)。

    【讨论】:

    • 解决了!谢谢!非常感谢您回答中的警告消息和文档链接!
    猜你喜欢
    • 2019-12-20
    • 2020-06-25
    • 2020-12-01
    • 2013-07-03
    • 2016-06-15
    • 2012-11-12
    • 1970-01-01
    • 2020-06-19
    • 2019-03-25
    相关资源
    最近更新 更多