为图创建相关的下拉菜单

时间:2019-06-15 11:23:19

标签: r plotly dropdown chained

我正在使用R Studio,Plot_ly和Rmarkdown。
该网站是通过blogdown / blogdown_hugo建立的。

在数据框“ data_local_indices_m”中是列
“值”(具有每个日期的值,需要绘制),
“ data_date”(包含时间序列的日期),
“国家/地区”包含国家/地区名称(例如AUT)和
“大陆”(例如欧洲)。

我想要两个下拉菜单来更改绘制的图形:

第一个下拉列表应包含各大洲。 根据第一个下拉菜单中的选定值, 第二个下拉菜单应仅显示具有该值的国家/地区。

例如:

Dropdown1(大陆):
 -欧洲(已选择此值)

Dropdown2(国家/地区):
-GER
-AUT
-ITA
...

我基本上有两个带有各自内容的下拉菜单,但我不知道如何使它们相互依赖。
此外,整个事物需要可变:
如果添加了一个新国家,它会自动出现(在下拉列表“国家”中,如果有新大陆,则应在下拉列表“大陆”中添加该内容)

设法使用相应的标签创建了两个下拉菜单,但它们并不相互依赖。

我只留下下面的代码。这是一种非常可悲的方法,但是它至少会创建下拉字段(彼此不依赖)。请随时提供一个更好的示例。也许将代码用作基本思想。

 continents <- c("Africa", "Asia", "Australia", "Europe", "North America", "South America")

 p2 <- Data_local_indices_m %>% 
  unnest(.sep = "_") %>%
  mutate(data_date=as.yearmon(data_date)) %>% 
  select(country,data_date,IS_data_turb) %>%
  plot_ly(
    mode = 'lines', 
    x = ~data_date, 
    y = ~IS_data_turb,
    transforms = list(
      list(
        type = 'filter', 
        target = ~country, 
        operation = '==', 
        value = unique(Data_local_indices_m$country)[1]))) %>% 
  layout(
    updatemenus = list(list(
      active = 3,
         y = 0.9,
         buttons = list(

           list(method = "restyle",
                args = list("visible", list(FALSE, TRUE)),
                label = continents[1]),

           list(method = "restyle",
                args = list("visible", list(FALSE, TRUE)),
                label = continents[2]), 

           list(method = "restyle",
                args = list("visible", list(FALSE, TRUE)),
                label = continents[3]),

           list(method = "restyle",
                args = list("visible", list(TRUE, FALSE)),
                label = continents[4]),

           list(method = "restyle",
                args = list("visible", list(FALSE, TRUE)),
                label = continents[5]),

           list(method = "restyle",
                args = list("visible", list(FALSE, TRUE)),
                label = continents[6]))),

       list(
         #active = 0,
         y = 0.8,
         x = -0.101,
         buttons = list(
             list(
                method = "restyle",
                args = list("transforms[0].value", unique(Data_local_indices_m$country)[1]),
                label = unique(Data_local_indices_m$country)[1]),

           list(method = "restyle",
                args = list("transforms[0].value", unique(Data_local_indices_m$country)[2]),
                label = unique(Data_local_indices_m$country)[2]),

           list(method = "restyle",
                args = list("transforms[0].value", unique(Data_local_indices_m$country)[3]),
                label = unique(Data_local_indices_m$country)[3]),

           list(method = "restyle",
                args = list("transforms[0].value", unique(Data_local_indices_m$country)[4]),
                label = unique(Data_local_indices_m$country)[4])
           )
         )
     )
   )

Dropdown1:“欧洲” 下拉菜单2:只有拥有“欧洲”大陆的可选国家/地区

->显示了相应国家/地区的图。

Packages in library ‘/home/rstudio-user/R/x86_64-pc-linux-gnu-library/3.6’:

anytime                     Anything to 'POSIXct' or 'Date' Converter
askpass                     Safe Password Entry for R, Git, and SSH
assertthat                  Easy Pre and Post Assertions
backports                   Reimplementations of Functions Introduced Since R-3.0.0
base64enc                   Tools for base64 encoding
BH                          Boost C++ Header Files
bitops                      Bitwise Operations
blogdown                    Create Blogs and Websites with R Markdown
bookdown                    Authoring Books and Technical Documents with R Markdown
Boom                        Bayesian Object Oriented Modeling
BoomSpikeSlab               MCMC for Spike and Slab Regression
broom                       Convert Statistical Analysis Objects into Tidy Tibbles
bsts                        Bayesian Structural Time Series
callr                       Call R from R
cellranger                  Translate Spreadsheet Cell Ranges to Rows and Columns
cli                         Helpers for Developing Command Line Interfaces
clipr                       Read and Write from the System Clipboard
clisymbols                  Unicode Symbols at the R Prompt
colorspace                  A Toolbox for Manipulating and Assessing Colors and
                            Palettes
crayon                      Colored Terminal Output
crosstalk                   Inter-Widget Interactivity for HTML Widgets
cubature                    Adaptive Multivariate Integration over Hypercubes
curl                        A Modern and Flexible Web Client for R
data.table                  Extension of `data.frame`
DBI                         R Database Interface
dbplyr                      A 'dplyr' Back End for Databases
DEoptimR                    Differential Evolution Optimization in Pure R
desc                        Manipulate DESCRIPTION Files
devtools                    Tools to Make Developing R Packages Easier
digest                      Create Compact Hash Digests of R Objects
dplyr                       A Grammar of Data Manipulation
DT                          A Wrapper of the JavaScript Library 'DataTables'
ecodist                     Dissimilarity-Based Functions for Ecological Analysis
ellipsis                    Tools for Working with ...
energy                      E-Statistics: Multivariate Inference via the Energy of
                            Data
evaluate                    Parsing and Evaluation Tools that Provide More Details
                            than the Default
fansi                       ANSI Control Sequence Aware String Functions
fAssets                     Rmetrics - Analysing and Modelling Financial Assets
fBasics                     Rmetrics - Markets and Basic Statistics
fMultivar                   Rmetrics - Analysing and Modeling Multivariate
                            Financial Return Distributions
forcats                     Tools for Working with Categorical Variables (Factors)
forecast                    Forecasting Functions for Time Series and Linear Models
fracdiff                    Fractionally differenced ARIMA aka ARFIMA(p,d,q) models
fs                          Cross-Platform File System Operations Based on 'libuv'
generics                    Common S3 Generics not Provided by Base R Methods
                            Related to Model Fitting
ggplot2                     Create Elegant Data Visualisations Using the Grammar of
                            Graphics
gh                          'GitHub' 'API'
git2r                       Provides Access to Git Repositories
glue                        Interpreted String Literals
googleVis                   R Interface to Google Charts
gss                         General Smoothing Splines
gtable                      Arrange 'Grobs' in Tables
haven                       Import and Export 'SPSS', 'Stata' and 'SAS' Files
hexbin                      Hexagonal Binning Routines
highr                       Syntax Highlighting for R Source Code
hms                         Pretty Time of Day
htmltools                   Tools for HTML
htmlwidgets                 HTML Widgets for R
httpuv                      HTTP and WebSocket Server Library
httr                        Tools for Working with URLs and HTTP
igraph                      Network Analysis and Visualization
ini                         Read and Write '.ini' Files
jomo                        Multilevel Joint Modelling Multiple Imputation
jsonlite                    A Robust, High Performance JSON Parser and Generator
                            for R
knitr                       A General-Purpose Package for Dynamic Report Generation
                            in R
labeling                    Axis Labeling
later                       Utilities for Delaying Function Execution
lazyeval                    Lazy (Non-Standard) Evaluation
lme4                        Linear Mixed-Effects Models using 'Eigen' and S4
lmtest                      Testing Linear Regression Models
lubridate                   Make Dealing with Dates a Little Easier
magrittr                    A Forward-Pipe Operator for R
mailR                       A Utility to Send Emails from R
markdown                    'Markdown' Rendering for R
memoise                     Memoisation of Functions
mice                        Multivariate Imputation by Chained Equations
mime                        Map Filenames to MIME Types
minqa                       Derivative-free optimization algorithms by quadratic
                            approximation
mitml                       Tools for Multiple Imputation in Multilevel Modeling
mnormt                      The Multivariate Normal and t Distributions
modelr                      Modelling Functions that Work with the Pipe
munsell                     Utilities for Using Munsell Colours
mvnormtest                  Normality test for multivariate variables
mvtnorm                     Multivariate Normal and t Distributions
nleqslv                     Solve Systems of Nonlinear Equations
nloptr                      R Interface to NLopt
numDeriv                    Accurate Numerical Derivatives
OECD                        Search and Extract Data from the OECD
openssl                     Toolkit for Encryption, Signatures and Certificates
                            Based on OpenSSL
ordinal                     Regression Models for Ordinal Data
pacman                      Package Management Tool
padr                        Quickly Get Datetime Data Ready for Analysis
pan                         Multiple Imputation for Multivariate Panel or Clustered
                            Data
PerformanceAnalytics        Econometric Tools for Performance and Risk Analysis
pillar                      Coloured Formatting for Columns
pkgbuild                    Find Tools Needed to Build R Packages
pkgconfig                   Private Configuration for 'R' Packages
pkgload                     Simulate Package Installation and Attach
plogr                       The 'plog' C++ Logging Library
plotly                      Create Interactive Web Graphics via 'plotly.js'
plyr                        Tools for Splitting, Applying and Combining Data
prettyunits                 Pretty, Human Readable Formatting of Quantities
processx                    Execute and Control System Processes
progress                    Terminal Progress Bars
promises                    Abstractions for Promise-Based Asynchronous Programming
ps                          List, Query, Manipulate System Processes
purrr                       Functional Programming Tools
quadprog                    Functions to Solve Quadratic Programming Problems
Quandl                      API Wrapper for Quandl.com
quantmod                    Quantitative Financial Modelling Framework
R.methodsS3                 S3 Methods Simplified
R.oo                        R Object-Oriented Programming with or without
                            References
R.utils                     Various Programming Utilities
R6                          Encapsulated Classes with Reference Semantics
RApiDatetime                R API Datetime
rcmdcheck                   Run 'R CMD check' from 'R' and Capture Results
RColorBrewer                ColorBrewer Palettes
Rcpp                        Seamless R and C++ Integration
RcppEigen                   'Rcpp' Integration for the 'Eigen' Templated Linear
                            Algebra Library
RCurl                       General Network (HTTP/FTP/...) Client Interface for R
readr                       Read Rectangular Text Data
readxl                      Read Excel Files
rematch                     Match Regular Expressions with a Nicer 'API'
remotes                     R Package Installation from Remote Repositories,
                            Including 'GitHub'
reprex                      Prepare Reproducible Example Code via the Clipboard
reshape2                    Flexibly Reshape Data: A Reboot of the Reshape Package
rJava                       Low-Level R to Java Interface
RJSONIO                     Serialize R Objects to JSON, JavaScript Object Notation
rlang                       Functions for Base Types and Core R and 'Tidyverse'
                            Features
rmarkdown                   Dynamic Documents for R
robustbase                  Basic Robust Statistics
rprojroot                   Finding Files in Project Subdirectories
rsdmx                       Tools for Reading SDMX Data and Metadata
rstudioapi                  Safely Access the RStudio API
rvest                       Easily Harvest (Scrape) Web Pages
scales                      Scale Functions for Visualization
selectr                     Translate CSS Selectors to XPath Expressions
servr                       A Simple HTTP Server to Serve Static Files or Dynamic
                            Documents
sessioninfo                 R Session Information
shiny                       Web Application Framework for R
sn                          The Skew-Normal and Related Distributions Such as the
                            Skew-t
sourcetools                 Tools for Reading, Tokenizing and Parsing R Code
stabledist                  Stable Distribution Functions
stringi                     Character String Processing Facilities
stringr                     Simple, Consistent Wrappers for Common String
                            Operations
sys                         Powerful and Reliable Tools for Running System Commands
                            in R
tibble                      Simple Data Frames
tidyquant                   Tidy Quantitative Financial Analysis
tidyr                       Easily Tidy Data with 'spread()' and 'gather()'
                            Functions
tidyselect                  Select from a Set of Strings
tidyverse                   Easily Install and Load the 'Tidyverse'
timeDate                    Rmetrics - Chronological and Calendar Objects
timeSeries                  Rmetrics - Financial Time Series Objects
timetk                      A Tool Kit for Working with Time Series in R
tinytex                     Helper Functions to Install and Maintain 'TeX Live',
                            and Compile 'LaTeX' Documents
tseries                     Time Series Analysis and Computational Finance
tsibble                     Tidy Temporal Data Frames and Tools
TTR                         Technical Trading Rules
ucminf                      General-Purpose Unconstrained Non-Linear Optimization
uncertaintymeasures         Functions to create uncertainty measures using
                            turbulence
urca                        Unit Root and Cointegration Tests for Time Series Data
usethis                     Automate Package and Project Setup
utf8                        Unicode Text Processing
vctrs                       Vector Helpers
viridisLite                 Default Color Maps from 'matplotlib' (Lite Version)
whisker                     {{mustache}} for R, logicless templating
withr                       Run Code 'With' Temporarily Modified Global State
xfun                        Miscellaneous Functions by 'Yihui Xie'
XML                         Tools for Parsing and Generating XML Within R and
                            S-Plus
xml2                        Parse XML
xopen                       Open System Files, 'URLs', Anything
xtable                      Export Tables to LaTeX or HTML
xts                         eXtensible Time Series
yaml                        Methods to Convert R Data to YAML and Back
zeallot                     Multiple, Unpacking, and Destructuring Assignment
zoo                         S3 Infrastructure for Regular and Irregular Time Series
                            (Z's Ordered Observations)

Packages in library ‘/opt/R/3.6.0/lib/R/library’:

base                        The R Base Package
boot                        Bootstrap Functions (Originally by Angelo Canty for S)
class                       Functions for Classification
cluster                     "Finding Groups in Data": Cluster Analysis Extended
                            Rousseeuw et al.
codetools                   Code Analysis Tools for R
compiler                    The R Compiler Package
datasets                    The R Datasets Package
foreign                     Read Data Stored by 'Minitab', 'S', 'SAS', 'SPSS',
                            'Stata', 'Systat', 'Weka', 'dBase', ...
graphics                    The R Graphics Package
grDevices                   The R Graphics Devices and Support for Colours and
                            Fonts
grid                        The Grid Graphics Package
KernSmooth                  Functions for Kernel Smoothing Supporting Wand & Jones
                            (1995)
lattice                     Trellis Graphics for R
MASS                        Support Functions and Datasets for Venables and
                            Ripley's MASS
Matrix                      Sparse and Dense Matrix Classes and Methods
methods                     Formal Methods and Classes
mgcv                        Mixed GAM Computation Vehicle with Automatic Smoothness
                            Estimation
nlme                        Linear and Nonlinear Mixed Effects Models
nnet                        Feed-Forward Neural Networks and Multinomial Log-Linear
                            Models
parallel                    Support for Parallel computation in R
rpart                       Recursive Partitioning and Regression Trees
spatial                     Functions for Kriging and Point Pattern Analysis
splines                     Regression Spline Functions and Classes
stats                       The R Stats Package
stats4                      Statistical Functions using S4 Classes
survival                    Survival Analysis
tcltk                       Tcl/Tk Interface
tools                       Tools for Package Development
utils                       The R Utils Package

1 个答案:

答案 0 :(得分:0)

您的代码确实很大。我将用一个简单的例子来说明这个想法。

您可以临时保存所选的大陆。之后,您只能选择与所选大洲相对应的国家/地区,因此在secound下拉菜单中只能在正确的国家/地区之间进行选择。像这样:

# some data
df <- data.frame(continent= c("europe", "europe", "asia", "asia"), country= c("italy", "germany", "china", "india"))
df
  continent country
1    europe   italy
2    europe germany
3      asia   china
4      asia   india

# now choose some continent (you will make this as a dropdown menu)
continent_choosen <- "europe"

# choosing from the possible countries
df$country[df$continent == continent_choosen]
italy germany

对于可能的城市或可能的郊区等都存在相同的想法。