1

I want to create a bar graph with plotly that shows the age group on the x axis and the prop on the y axis. Then I want to have a dropdown mwenu that update the figure by reg. My actual data has 20 regions so it will be great to a function with a loop that create the menu automatically. Something similar to this

Mdf <- Mdf <- data.frame(age=c(15,20,25,30,35,40,45),cases=c(1200,1110,2233,1445,1323,1510,910),py=c(10101,12465,452424,14240,1544,1574,1154))
Mdf <- rbind(Mdf,Mdf)
Mdf$cases[8:14] <- Mdf$cases[1:7]+3
Mdf$prop <- (Mdf$cases / Mdf$py)*100
Mdf$reg <- c(rep(1,7),rep(2,7))

library(tidyverse)
library(plotly)
  
  p <- 
    plot_ly(
    y = Mdf$prop,
    x = Mdf$age,
    type = "bar"
  ) 
  

I would appreciate your help

1 Answer 1

1

Using the function you provided in the link, you get the following

Mdf <- Mdf <- data.frame(age=c(15,20,25,30,35,40,45),cases=c(1200,1110,2233,1445,1323,1510,910),py=c(10101,12465,452424,14240,1544,1574,1154))
Mdf <- rbind(Mdf,Mdf)
Mdf$cases[8:14] <- Mdf$cases[1:7]+553
Mdf$prop <- (Mdf$cases / Mdf$py)*100
Mdf$reg <- c(rep("a",7),rep("b",7))

library(tidyverse)
library(plotly)

p <- Mdf %>% 
  plot_ly(
    y = ~prop,
    x = ~age,
    text = ~reg,
    type = "bar",
    hoverinfo = 'text',
    transforms = list(
      list(
        type = 'filter',
        target = ~reg,
        operation = '=',
        value = unique(Mdf$reg)[1]
      )
    )) %>% layout(
      updatemenus = get_menu_list(unique(Mdf$reg))
    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.