我正在遵循R shiny Aesthetics must be either length 1 or the same as the data (8): y中给出的解决方案,以解决这个烦人的问题,我已经很高兴地解决了该问题。
我要解决的下一个问题是我希望我的地块有一个反应性的图例-我只希望图例显示实际选择的内容并在图上显示
我还想将线条的颜色设置为我想要的颜色。最后,我要确保图例始终按我指定的顺序
这是一个可复制的示例(注释掉的代码是我解决自己的问题的尝试。
如您所见,注释掉的部分是我如何获取所需的图例和颜色的方法:
library(shiny)
library(tidyverse)
library(reshape2)
library(scales)
time <- seq(-9, 60, 1)
var1 <- rnorm(70, 35, 2)
var2 <- rnorm(70, 50, 2)
var3 <- rnorm(70, 24, 2)
var4 <- rnorm(70, 17, 2)
data <- data.frame(time = time,
var1 = var1,
var2 = var2,
var3 = var3,
var4 = var4)
datamelt <- melt(data, "time")
p <- ggplot(datamelt, aes(x = time, y = value, color = variable)) +
# scale_color_manual(values = c(
# 'first' = 'red',
# 'second' = 'blue',
# 'third' = 'green',
# 'fourth' = 'orange'
# ),
# breaks = c("first", "second", "third", "fourth")) +
# labs(color = 'Legend') +
theme_classic() +
theme(axis.ticks = element_blank()) +
labs(title = 'it means nothing',
subtitle = 'these are made up data') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)) +
scale_x_continuous(name ="a y variable", breaks = seq(-9, 60, 1)) +
scale_y_continuous(name = "yep an x variable",
breaks = seq(0, 60, 5), labels = comma) + geom_blank()
ui <- fluidPage(
titlePanel("trying to make this work"),
sidebarLayout(
sidebarPanel(
checkboxGroupInput("whichone", "Choose something:",
choiceNames = c("first",
"second",
"third",
"fourth"),
choiceValues = c("var1",
"var2",
"var3",
"var4"))
),
###the plot
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output) {
output$plot <- renderPlot({
data_filtered <- datamelt %>% filter(variable %in% input$whichone)
p + geom_line(data = data_filtered)
})
}
shinyApp(ui, server)
答案 0 :(得分:2)
之所以会出现问题,是因为$products = array_reduce($products, function ($carry, $product) {
if (!isset($carry[$product['api_id']])) {
$carry[$product['api_id']] = $product;
}
else {
$carry[$product['api_id']]['amount'] += $product['amount'];
$carry[$product['api_id']]['cost_price'] += $product['cost_price'];
}
return $carry;
}, []);
使用了所有因子级别,这些因子级别在您进行过滤时会保持不变。因此,您需要先降低这些级别。
第二,您将在所有级别上静态生成图。因此,您还需要更新数据,以使ggplot
知道在图例中显示哪些级别。放在一起可以使用以下内容:
ggplot
注意。这种方法具有讨厌的(?)副作用,即如果您不选择任何数据来显示,则只会看到一个空白画布。也可以对此进行补救,但是需要对代码逻辑进行一些更改(基本上将server <- function(input, output) {
output$plot <- renderPlot({
## 1. drop unused levels from teh filtered database
data_filtered <- datamelt %>% filter(variable %in% input$whichone) %>%
droplevels()
## 2. tell ggplot to update the data
p %+% data_filtered + geom_line()
})
}
的结构移到ggplot
内)