Создание зависимых выпадающих меню для графиков - PullRequest
0 голосов
/ 15 июня 2019

Я использую R Studio, Plot_ly и Rmarkdown.
Сайт настраивается через blogdown / blogdown_hugo.

В кадре данных "data_local_indices_m" находятся столбцы
«значение» (которое имеет значение для каждой даты, которая должна быть нанесена на график),
«data_date» (содержит дату временного ряда),
«страна» содержит название страны (например, AUT) и
"континент" (например, Европа).

Я хочу, чтобы два раскрывающихся меню изменили построенный график:

1-й выпадающий список должен содержать континенты. На основе выбранного значения в первом раскрывающемся меню, в 2-й выпадающий список должен отображаться только в тех странах, которые имеют это значение.

например:.

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: "Европа" Dropdown2: только выбираемые страны, имеющие континент "Европа"

-> Отображается график соответствующей страны.

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 голосов
/ 15 июня 2019

Ваш код действительно большой. Я буду использовать простой пример, чтобы проиллюстрировать идею.

Вы можете временно сохранить выбранный континент. После этого вы можете выбрать только те страны, которые соответствуют выбранному континенту, так что в раскрывающемся меню 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

Та же идея применяется для возможных городов или пригородов и т. Д.

...