newData() is a dynamic generated data frame by a reactive statement based on user inputs:
selectInput("year", "Year", c("2019", "2020", "2021"), selected = "2021")
selectInput("fruit", "Fruit", names(FruitSales$fname), selected = "Pineapple")
For year 2021, for example, newData() is:
fruit x2021_sales
1 Pineapple 42
2 Orange 36
3 Carrot 56
4 Onion 82
5 Avocado 94
6 Mushroom 24
7 Apple 23
8 Banana 46
9 Mango 61
10 Strawberry 43
Note the name of the second column. It is generated by concatenating "x", input$year, and "_sales".
I want to plot a treemap of newData() with plotly: labels = ~get(input$fruit), values = ~x20yy_sales
. I've tried a couple of ways. The first is to use ggplot to generate a treemap and then ggplotly it. It didn't work because somehow geom_treemap_text wasn't compatible with plotly. The second is below:
renderPlotly({
treeplot <- plot_ly(NewData(),
labels = ~get(input$fruit),
parents = ~NA,
# values = ~x2021_sales, ## --> works
# values = paste0("x", input$year, "_sales"), ## --> doesn't work
# values = paste0("x", eval(as.name(input$year)), "_sales"), ## --> doesn't work
type = "treemap"
)
treeplot
})
Without values
, the dashboard worked and gave me a treemap with euqal-sized blocks as expected. If values = ~x2021_sales
was hard-coded in, it also worked. but when I tried to pass input$year
from the input sidebar to values
, nothing worked. Anyone knows what to do?
Edit 1: x = as.formula(paste0("~",input$x))
suggested by the moderator returned errors, something to the effect of "invalid formula."
Edit 2: The trick of labels = ~get(input$fruit)
was borrowed from here https://stackoverflow.com/questions/66337613/selective-y-variable-in-shiny-plotly-output and here https://stackoverflow.com/questions/63543144/how-to-make-a-plotly-chart-of-variables-selected-by-a-user-in-shiny-or-flexdahsb.