[英]R: How to change plot background color for a specific range in ggvis shiny app
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))
要使矩形的宽度随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
或逻辑向量(使用+
转换为数字)并将其用作opacity
参数,
vis = reactive({
data = dataInput()
## Option 1: and use layer_points(data=inrange)
## inrange <- with(dataInput(), dataInput()[score >=80 | score <= 50,])
## Options 2, with opacity=~inrange
inrange = +with(data, score >=80 | score <= 50)
data %>%
ggvis(x = ~year, y = ~score) %>%
scale_numeric("y",domain = c(40,120)) %>%
layer_points(opacity = ~inrange) %>%
layer_lines() %>%
make_rect(lims=rectLims)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.