ggvis
创建,用户可以从inputSelect
中选择学生姓名。在图中,我想要更改特定分数范围内的背景颜色。例如,每个情节中的 ,分数高于80或低于50的情节背景颜色用蓝色突出显示(参见附图)。我试图使用layer_rects()
添加图层并在绘图上绘制矩形,但问题是如果选择不同的学生,x轴的值会改变。任何人之前做过这个或者有什么想法吗?如果我只想要那个得分范围内的积分弹出,是否有可能?非常感谢!
library(shiny)
library(ggvis)
df <- data.frame(Student = c("a","a","a","a","a","b","b","b","b","b","c","c","c","c"),
year = c(seq(2001,2005,1),seq(2010,2014,1),seq(2012,2015,1)),
score = runif(14,min = 50,max = 100), stringsAsFactors=F)
ui = (fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("stu","Choose Student",
choice = unique(df$Student))
),
mainPanel(ggvisOutput("plot"))
)
)
)
server = function(input,output,session){
dataInput = reactive({
gg = df[which(df$Student == input$stu),]
})
vis = reactive({
data = dataInput()
data %>%
ggvis(x = ~year, y = ~score) %>%
scale_numeric("y",domain = c(40,120))%>%
layer_lines()
})
vis %>% bind_shiny("plot")
}
runApp(list(ui = ui, server = server))
答案 0 :(得分:1)
要使矩形的宽度随x轴变量而变化,可以使用x = ~min(year)
和x2 = ~max(year)
。我不确定如何使变量依赖于当前的比例限制,这似乎是一个更好的解决方案。但是,这应该有效。例如,下面的矩形将是
layer_rects(x = ~min(year), x2 =~max(year),
y = 40-3.5, y2 = 50, opacity := 0.05, fill := "blue")
它没有针对不同的限制进行矢量化(至少看起来不是这样),因此您可以编写一个函数来简化多个矩形。整个服务器看起来像
shinyServer(function(input,output,session){
dataInput = reactive({
gg = df[which(df$Student == input$stu),]
})
buffer <- 3.5 # set to make the rectangle reach the scale boundaries
rectLims <- list(lower=c(40-buffer, 80), upper=c(50, 120+buffer))
make_rect <- function(vis, lims, buffer=buffer) {
for (i in seq_along(lims$lower))
vis <- layer_rects(vis, x = ~min(year), x2 =~max(year),
y = rectLims$lower[i], y2 = rectLims$upper[i],
opacity := 0.05, fill := "blue")
vis
}
vis = reactive({
data = dataInput()
data %>%
ggvis(x = ~year, y = ~score) %>%
scale_numeric("y",domain = c(40,120)) %>%
layer_points()%>%
layer_lines() %>%
make_rect(lims=rectLims)
})
vis %>% bind_shiny("plot")
})
对于第二个问题,如果您只希望点数显示在该范围内,您可以将数据的子集用于layer_points
或逻辑向量(使用{{1}转换为数字})并将其用作+
参数,
opacity