我正在创建ggplot
在R Shiny中使用的交互式折线图。我这样做的方式是让用户在UI中使用选择器输入选择他们想要在绘图中看到的值。然后在服务器中,根据用户的选择对数据进行过滤。我在ggplot
使用中指定了x轴scale_x_continuous
。我将序列设置为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)
有几种方法可以设置轴上的限制:您快到了!
要在通话scale_x_continuous
中你的renderPlot()
函数只设置轴的断裂(种它是如何标记)。您想要设置限制,您可以scale_x_continuous
通过参数在函数中进行设置limits=
。请参阅文档以获取更多信息,但这应该对您有用:
scale_x_continuous(breaks = seq(0,24, by=1), limits = c(0,24))
另外,如果您只想设置限制,但轴上的默认“中断”很好,则可以xlim(0,24)
代替使用来更轻松地访问x和y限制scale_x_continuous
。
但是请务必小心:设置轴的限制将导致该数据丢失-意味着该数据将不再用于任何其他统计功能。如果仍然需要将该数据保留在图中的其他统计功能,则可以使用coord_cartesian()
(请参阅此处的文档)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句