I am trying to add a plot in r shiny app using plotly. I can add it when I add the traces manually. But now I want to add the traces dynamically. Also I dont want to add traces for all columns. I just want to add traces for columns which end with sale. Below is the code so far. This doesnt add all the traces. How can I add all the traces which just which have _sales in them.
output$pacingplot <- renderPlotly({
colNames <- names(Delivery_data)[-1] #Assuming Date is the first column
print(colNames)
p <- plotly::plot_ly(x = ~Delivery_data$Date, type = "scatter",
mode = "lines")
for(trace in colNames){
p <- p %>% plotly::add_trace(y = as.formula(paste0("~`", trace, "`")), name = trace)
}
p %>%
layout(title = "Impressions Over Time",
xaxis = list(title = "Date"),
yaxis = list (title = "Impressions"))
})
Below are the colnames (This doenst include date since I removed the first column):
[1] "apples_sales" "apples_count" "bananas_sales" "bananas_count" "oranges_sales" "oranges_count" "peach_sales" "peach_count"
Below is the data
Delivery_data <- data.frame(
Date = c("2019-08-19", "2019-08-20", "2019-08-21",
"2019-08-22", "2019-08-23", "2019-08-24"),
apples_sales = c(10882.05495, 516.29755, 949.4084, 3950.5318,
2034.02055, 1770.50415),
apples_count = c(239575, 11281, 20150, 88679, 45672, 38553),
peach_sales = c(0, 0, 0, 0, 0, 0),
peach_count = c(0, 0, 0, 0, 0, 0),
bananas_sales = c(9643.600102, 6041.538067, 5371.758106, 5238.308826,
4994.43054, 5001.303585),
bananas_count = c(630827, 510219, 565440, 576678, 518081, 551733),
oranges_sales = c(0, 1694.44, 9105.89, 6179.47, 7366.31, 6275.43),
oranges_count = c(0, 684210, 3695182, 2501560, 2984563, 2531400)
)
outputcontainer? (You should also add alibrary(plotly)line.plotly-user, so the style of "create a function as a list-leaf" and then "use it" is not particularly natural. I would need a full use case, i.e. what to do with that list item:output$pacingplot? When I throw your data at an empty list to which I add a "pacingplot"-element as an argument, I get:Error in eval(expr, data, expr_env) : object 'apples_sales' not found