gpt4 book ai didi

R:如何更改 ggvis Shiny 应用程序中特定范围的绘图背景颜色

转载 作者:行者123 更新时间:2023-12-04 11:26:07 26 4
gpt4 key购买 nike

我有一个像下面这样的简单 Shiny 的应用程序,你可以运行它。这些图由 ggvis 创建并且用户可以从inputSelect中选择学生姓名.在图中,我想更改特定分数范围内的背景颜色。例如,在每个地块中 , 分数高于 80 或低于 50 的绘图背景颜色以蓝色突出显示(见附图)。我试图使用 layer_rects() 添加图层并在绘图上绘制矩形,但问题是如果选择不同的学生,x 轴的值会改变。任何人以前做过这个或任何想法?如果我只想弹出该分数范围内的分数,是否有可能?非常感谢!
example pic

  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)
})

关于R:如何更改 ggvis Shiny 应用程序中特定范围的绘图背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33349513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com