英文:
Add a dropdown menu to plotly created bar chart using a loop
问题
我想使用Plotly创建一个条形图,x轴显示年龄组,y轴显示比例。然后,我想要一个下拉菜单,通过它可以根据地区更新图形。我的实际数据有20个地区,所以最好使用循环创建菜单的函数。类似于这个。
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 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
得分: 1
使用您在链接中提供的函数,您将得到以下结果:
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))
)
希望这有所帮助。如果您需要进一步的解释或帮助,请告诉我。
英文:
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))
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论