R 我的绘图下拉菜单没有';不适当地更新数据?
我第一次使用plotly创建了一个交互式图表,可以将RR 我的绘图下拉菜单没有';不适当地更新数据?,r,drop-down-menu,plotly,R,Drop Down Menu,Plotly,我第一次使用plotly创建了一个交互式图表,可以将Rtidykids包中的任何变量绘制为按状态分组的时间序列。这是我在plotly链中设置数据框对象格式的代码 kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv') kids_my_variables <- kids %>% piv
tidykids
包中的任何变量绘制为按状态分组的时间序列。这是我在plotly链中设置数据框对象格式的代码
kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv')
kids_my_variables <- kids %>% pivot_wider(id_cols = c('state','year') , names_from = 'variable' , values_from = 'inf_adj') %>% mutate(fips = fips(state), total = rowSums(.[3:25], na.rm = TRUE), education_agg = PK12ed + highered + edsubs + edservs + pell + HeadStartPriv, education_pcnt = (round(education_agg / total, 2)*100) , lib_pcnt = ((lib / total)*100) , park_pcnt = (round(parkrec / total,2))*100) %>% select(fips, state, year, education = education_pcnt, libraries = lib_pcnt, `parks & rec` = park_pcnt, total) %>% filter(year != 1997)
plot_ly(kids_my_variables, x = ~year) %>%
add_lines(y = ~education, color = ~state) %>%
add_lines(y = ~`parks & rec`, color = ~state, visible = FALSE) %>%
layout(
title = "% of total child spending",
showlegend = TRUE,
updatemenus = list(
list(
buttons = list(
list(method = "restyle",
args = list(list(visible = list(TRUE, FALSE)),
list(yaxis = list(title = "Education"))),
label = "Education"),
list(method = "restyle",
args = list(list(visible = list(FALSE, TRUE)),
list(yaxis = list(title = "Parks & Rec"))),
label = "Parks & Rec")))
)
)
当我使用下拉菜单更改打印数据时,它会保留原始打印的数据。教育s/b的y轴范围为25-69。另一方面,Parks和rec从1-7开始s/from,但是使用下拉过滤器将绘图更新为Parks和rec时,我得到了这个结果
对于分组变量的每个级别(即状态),plotly的一个怪癖是希望您将
可见设置为TRUE
或FALSE
将两个rep()
s(一个表示true,一个表示false)连接到状态数似乎是目前我能找到的唯一解决方法
在更改数据和布局(y轴标题)时,还需要使用method=“update”
而不是restyle
这应该起作用:
plot_ly(kids_my_variables, x = ~year) %>%
add_lines(y = ~education, color = ~state) %>%
add_lines(y = ~`parks & rec`, color = ~state, visible = FALSE) %>%
layout(
title = "% of total child spending",
showlegend = TRUE,
updatemenus = list(
list(
buttons = list(
list(method = "update",
args = list(list(visible = c(rep(TRUE, length(unique(kids_my_variables$state))), rep(FALSE, length(unique(kids_my_variables$state))))),
list(yaxis = list(title = "Education"))),
label = "Education"),
list(method = "update",
args = list(list(visible = c(rep(FALSE, length(unique(kids_my_variables$state))), rep(TRUE, length(unique(kids_my_variables$state))))),
list(yaxis = list(title = "Parks & Rec"))),
label = "Parks & Rec")))
)
)