0

I am making a R Shiny App, which consists of 3 files (ui.R, server.R, global.R).

In the global.R file I have various functions in it, which create plots based on various inputs (ui.R). In server.R I call these functions. So far everything works. Now I want to place the same plot in another tabItem. When I run it, I don't see any plot at all.

Do you have any idea what I am doing wrong?

Here is my code:

**ui.R**:
```
library(shiny)
library(shinydashboard)
library(DT)
library(plotly)
library(quantmod)
library(tidyquant)
# Define UI for application that draws a histogram
shinyUI(
  dashboardPage(
    # Titel der App
    dashboardHeader(title = img(src = "logo2.png", height = "35px")),
    dashboardSidebar(
      tags$head(tags$style(HTML('
.skin-blue .main-sidebar{
background-color: #FFFFFF;
}
'))),
      # SidebarMenu
      sidebarMenu(
        menuItem("Porfolio bewerten", tabName = "portBe"),
        menuItem("Rendite maximieren", tabName = "rendmaxi"),
        menuItem("Risiko minimieren", tabName = "riskmini"),
        menuItem("Anleitung", tabName = "anleitung"),
        menuItem("Ueber uns", tabName = "ueber_uns")
      )
    ),
    # Aufbau des Interface
    dashboardBody(
      tabItems(
        tabItem("portBe",
                tabsetPanel(type = "tabs",
                            tabPanel("Eingaben",
                                     numericInput("btc","Bitcoin",value = 0,min = -10, max = 100),
                                     numericInput("gold","Gold",value = 0,min = 0, max = 100),
                                     numericInput("swissbonds","Schweizer Bonds",value = 0,min = 0, max = 100),
                                     numericInput("smi","SMI",value = 0,min = 0, max = 100),
                                     numericInput("sp500","SP500",value = 0,min = 0, max = 100),
                                     numericInput("us10","US 10y Bonds",value = 0,min = 0, max = 100),
                                     numericInput("usdchf","USD/CHF Devisen",value = 0,min = 0, max = 100)
                                     ),
                            tabPanel("Kuchendiagramm",
                                     plotlyOutput("piePlot",
                                                  width = "100%",
                                                  height = "100%")),
                            tabPanel("Detailansicht",
                                     DT::dataTableOutput("bwt")),
                            tabPanel("Historie dieses Portfolios",
                                     plotlyOutput("chartPlot",
                                                  width = "100%",
                                                  height = "100%"),
                                     plotlyOutput("normalP",
                                                  height = "100%",
                                                  width = "100%")),
                            tabPanel("Kennzahlen", "Hier kommen ein Plot und sonstige Sachen hin"))),
        tabItem("rendmaxi",
                tabsetPanel(type = "tabs",
                            tabPanel("Eingaben",
                                     sliderInput("ren", "Ihr gewuenschtes Risiko:", 0,25,0,0.1),
                                     numericInput("wert", "Wieviel wollen Sie anlegen?", 0),
                                     radioButtons("boarder1", "Wollen Sie Grenzen setzten?",
                                                  choices = c("Ja", "Nein"), selected = "Nein"),
                                     conditionalPanel(condition = "input.boarder1 == 'Ja'",
                                                      numericInput("bts_boarder", "Wieviel Prozent wollen Sie in Bitcoin haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("gold_boarder", "Wieviel Prozent wollen Sie in Gold haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("swissbonds_boarder", "Wieviel Prozent wollen Sie in Schweizer Bonds haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("smi_boarder", "Wieviel Prozent wollen Sie im SMI haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("sp500_boarder", "Wieviel Prozent wollen Sie im S&P 500 haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("us10_boarder", "Wieviel Prozent wollen Sie in US 10y Bonds haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("usdchf_boarder", "Wieviel Prozent wollen Sie in USD/CHF Devisen haben?",
                                                                   value = 0, min = 0, max = 100))),
                            
                            tabPanel("Kuchendiagramm", 
                                     "Test"),
                            tabPanel("Detailansicht", "Hier kommt eine Tabelle"),
                            tabPanel("Historie des Portfolios", "Hier kommt ein Linienchart"))),
        tabItem("riskmini",
                tabsetPanel(type = "tabs",
                            tabPanel("Eingaben",
                                     sliderInput("risk", "Ihre gewuenschte Rendite:", 0,25,0,1),
                                     numericInput("wert", "Wieviel wolen Sie anlegen?",0),
                                     radioButtons("boarder2", "Wollen Sie Grenzen setzten?",
                                                  choices = c("Ja", "Nein"), selected = "Nein"),
                                     conditionalPanel(condition = "input.boarder2 == 'Ja'",
                                                      numericInput("bts_boarder", "Wieviel Prozent wollen Sie in Bitcoin haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("gold_boarder", "Wieviel Prozent wollen Sie in Gold haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("swissbonds_boarder", "Wieviel Prozent wollen Sie in Schweizer Bonds haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("smi_boarder", "Wieviel Prozent wollen Sie im SMI haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("sp500_boarder", "Wieviel Prozent wollen Sie im S&P 500 haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("us10_boarder", "Wieviel Prozent wollen Sie in US 10y Bonds haben?",
                                                                   value = 0, min = 0, max = 100),
                                                      numericInput("usdchf_boarder", "Wieviel Prozent wollen Sie in USD/CHF Devisen haben?",
                                                                   value = 0, min = 0, max = 100))),
                            
                            tabPanel("Kuchendiagramm", "Hier kommt ein Diagramm"),
                            tabPanel("Detailansicht", "Hier kommt eine Tablle"),
                            tabPanel("Historie des Portfolios", "Hier kommt ein Linienchart"))),
        tabItem("anleitung",
                tabsetPanel(type = "tabs",
                            tabPanel("Portfolio bewerten", "Anleitung fuer die Bewertung des Portfolios"),
                            tabPanel("Rendite maximieren", "Anleitung um die Rendite zu maximieren"),
                            tabPanel("Risiko minimieren", "Anleitung um das Risiko zu minimieren"))),
        tabItem("ueber_uns",
                img(src = "ueber_uns.png", height = "500px"))
        
      )
    )
)    
)
```
**server.R**
Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon.
```
library(shiny)
library(shinydashboard)
library(DT)
library(plotly)
library(quantmod)
library(tidyquant)


shinyServer(function(input, output) {
  source("global.R", local = T)
  output$piePlot <- renderPlotly({
    pieall()
  })
  
  output$bwt <- DT::renderDataTable(
    
    DT::datatable(data = data.frame(Asset = c("Bitcoin","Gold", "Schweizer Bonds","SMI", "SP500", "US 10y Bonds", "USD/CHF Devisen"),
                                    Prozent = c(input$btc,input$gold,input$swissbonds,input$smi,input$sp500,input$us10,input$usdchf),
                                    
                                    Wert = c(input$btc,input$gold,input$swissbonds,input$smi,input$sp500,input$us10,input$usdchf)))
  )
  
  output$chartPlot <- renderPlotly({
    stockall()
  })
  
  output$normalP <- renderPlotly({
    normalChart()
  })

})
Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon.
```

**global.R**
``` 
library(quantmod)
library(dplyr)
library(tidyr)
library(ggplot2)
library(lubridate)
library(ggthemes)
library(plotly) # To create interactive charts
library(xts)
library(RColorBrewer)
library(tseries)
library(tibble)
library(PerformanceAnalytics)
library(DEoptim)
library(shinyjs)
library(scales)
library(tidyquant) # To download the data
library(timetk) # To manipulate the data series


daten <- function(){
  # daten aus yahoo extrahieren
  options("getSymbols.warning4.0"=FALSE)
  options("getSymbols.yahoo.warning"=FALSE)
  
  getSymbols("^SSMI", from = '2014-09-22',to= Sys.Date(),warnings = FALSE,auto.assign = TRUE)
  getSymbols("GC=F", from = '2014-09-22',to= Sys.Date(),warnings = FALSE,auto.assign = TRUE)
  getSymbols("BTC-USD", from = '2014-09-22',to= Sys.Date(),warnings = FALSE,auto.assign = TRUE)
  getSymbols("^GSPC", from = '2014-09-22',to= Sys.Date(),warnings = FALSE,auto.assign = TRUE)
  getSymbols("CSBGC0.SW", from = '2014-09-22',to= Sys.Date(),warnings = FALSE,auto.assign = TRUE)
  getSymbols("^TNX", from = '2014-09-22',to= Sys.Date(),warnings = FALSE,auto.assign = TRUE)
  getSymbols("CHF=X", from = '2014-09-22',to= Sys.Date(),warnings = FALSE,auto.assign = TRUE)
  
  # Datensaetze umbenennen
  SMI <- SSMI
  GOLD <- `GC=F`
  BTC <- `BTC-USD`
  SP500 <- GSPC
  CH10YT <- CSBGC0.SW
  US10YT <- TNX
  USD_CHF <- `CHF=X`
  head(SMI)
  
  colnames(SMI) <- c("Open","High","Low","Close","Volume","Adjusted")
  colnames(GOLD) <- c("Open","High","Low","Close","Volume","Adjusted")
  colnames(BTC) <- c("Open","High","Low","Close","Volume","Adjusted")
  colnames(SP500) <- c("Open","High","Low","Close","Volume","Adjusted")
  colnames(CH10YT) <- c("Open","High","Low","Close","Volume","Adjusted")
  colnames(US10YT) <- c("Open","High","Low","Close","Volume","Adjusted")
  colnames(USD_CHF) <- c("Open","High","Low","Close","Volume","Adjusted")
  
  # alle NA zeilen loeschen
  SMI <- SMI[complete.cases(SMI), ]
  GOLD <- GOLD[complete.cases(GOLD), ]
  BTC <- BTC[complete.cases(BTC), ]
  SP500 <- SP500[complete.cases(SP500), ]
  CH10YT <- CH10YT[complete.cases(CH10YT), ]
  US10YT <- US10YT[complete.cases(US10YT), ]
  USD_CHF <- USD_CHF[complete.cases(USD_CHF), ]
  
  port.perfomance <- matrix(data = NA,nrow = length(SMI$Adjusted),ncol = 1)
  port.perfomance <- SMI$Adjusted
  port.perfomance <- merge(port.perfomance,SP500$Adjusted)
  port.perfomance <- merge(port.perfomance,BTC$Adjusted)
  port.perfomance <- merge(port.perfomance,GOLD$Adjusted)
  port.perfomance <- merge(port.perfomance,CH10YT$Adjusted)
  port.perfomance <- merge(port.perfomance,US10YT$Adjusted)
  port.perfomance <- merge(port.perfomance,USD_CHF$Adjusted)
  
  colnames(port.perfomance) <- c("SMI","SP500", "BTC","GOLD","CH10YT","US10YT","USD_CHF")
  rownames(port.perfomance) <- 1:length(port.perfomance$SMI)
  head(port.perfomance)
  port.perfomance <- port.perfomance[complete.cases(port.perfomance), ]
  port.perfomance
  port.perfomance <- as.data.frame(port.perfomance)
  
  port.perfomance$SMI.norm <- port.perfomance$SMI/port.perfomance$SMI[1]
  port.perfomance$SP500.norm <- port.perfomance$SP500/port.perfomance$SP500[1]
  port.perfomance$BTC.norm <- port.perfomance$BTC/port.perfomance$BTC[1]
  port.perfomance$GOLD.norm <- port.perfomance$GOLD/port.perfomance$GOLD[1]
  port.perfomance$CH10YT.norm <- port.perfomance$CH10YT/port.perfomance$CH10YT[1]
  port.perfomance$US10YT.norm <- port.perfomance$US10YT/port.perfomance$US10YT[1]
  port.perfomance$USD_CHF.norm <- port.perfomance$USD_CHF/port.perfomance$USD_CHF[1]
  
  port.perfomance$date <- rownames(port.perfomance)
  return(port.perfomance)
}

normalChart <- function(){
  port.perfomance <- daten()
  
  tickers = c("SMI", "SP500", "GOLD", "CH10YT", "US10YT", "USD_CHF")
  fig <- plot_ly(port.perfomance, type = 'scatter', mode = 'lines')%>%
    add_trace(x = ~date, y = ~SMI.norm, name = 'SMI')%>%
    add_trace(x = ~date, y = ~SP500.norm, name = 'SP500')%>%
    add_trace(x = ~date, y = ~GOLD.norm, name = 'GOLD')%>%
    add_trace(x = ~date, y = ~CH10YT.norm, name = 'CH10YT')%>%
    add_trace(x = ~date, y = ~US10YT.norm, name = 'US10YT')%>%
    add_trace(x = ~date, y = ~USD_CHF.norm, name = 'USD_CHF')%>%

    layout(title = 'custom tick labels',legend=list(title=list(text='variable')),
           xaxis = list(dtick = "M1", tickformat="%b<br>%Y",showticklabels = F), width = 1000)

  options(warn = -1)
  
  fig <- fig %>%
    layout(
      xaxis = list(zerolinecolor = '#ffff',
                   zerolinewidth = 2,
                   gridcolor = 'ffff'),
      yaxis = list(zerolinecolor = '#ffff',
                   zerolinewidth = 2,
                   gridcolor = 'ffff'),
      plot_bgcolor='#e5ecf6')
  
  return(fig)
}

stockall <- function(){
  port.perfomance <- daten()
  
  summe <- abs(sum(input$btc,input$gold,input$swissbonds,input$smi,input$sp500,input$us10,input$usdchf))
  
  gew <- c(input$smi/summe,input$sp500/summe,input$btc/summe,input$gold/summe,
           input$swissbonds/summe,input$us10/summe,input$usdchf/summe) # Gewichtungsvektor: muss 1,10,100 etc. geben, Laenge = 7
  # "SMI.Gewicht","SP500.Gewicht","BTC.Gewicht","GOLD.Gewicht","CH10YT.Gewicht","US10YT.Gewicht","USD_CHF.Gewicht"
  
  sum(gew)
  zaehler <- gew[1]*port.perfomance$SMI.norm+gew[2]*port.perfomance$SP500.norm+gew[3]*port.perfomance$BTC.norm+gew[4]*port.perfomance$GOLD.norm+gew[5]*port.perfomance$CH10YT.norm+gew[6]*port.perfomance$US10YT.norm+gew[7]*port.perfomance$USD_CHF.norm
  nenner <- gew[1]*port.perfomance$SMI.norm[1]+gew[2]*port.perfomance$SP500.norm[1]+gew[3]*port.perfomance$BTC.norm[1]+gew[4]*port.perfomance$GOLD.norm[1]+gew[5]*port.perfomance$CH10YT.norm[1]+gew[6]*port.perfomance$US10YT.norm[1]+gew[7]*port.perfomance$USD_CHF.norm[1]
  # Es ist egal ob fuer diese Berechnung der echte oder normierte Wert genommen wird
  port.perfomance$totalAssets <- zaehler/nenner
  # port.perfomance$totalAssets <- (gew[1]*all_assets$SMI.norm+gew[2]*all_assets$SP500.norm+gew[3]*all_assets$BTC+gew[4]*all_assets$GOLD) / (gew[1]*all_assets$SMI.norm+gew[2]*all_assets$SP500.norm+gew[3]*all_assets$BTC+gew[4]*all_assets$GOLD)[1]
  
  head(port.perfomance)
  # normiert die verschiedenen, addierten, normierten Assets wieder
  
  # Plot mit Schieberegler und Zeitraumauswahl
  fig <- plot_ly(port.perfomance, type = 'scatter', mode = 'lines')%>%
    add_trace(x = ~date, y = ~totalAssets)%>%
    layout(showlegend = F, title='Time Series with Range Slider and Selectors',
           xaxis = list(rangeslider = list(visible = T),
                        rangeselector=list(
                          buttons=list(
                            list(count=1, label="1m", step="month", stepmode="backward"),
                            list(count=6, label="6m", step="month", stepmode="backward"),
                            list(count=1, label="YTD", step="year", stepmode="todate"),
                            list(count=1, label="1y", step="year", stepmode="backward"),
                            list(step="all")
                          ))))
  
  fig <- fig %>%
    layout(
      xaxis = list(zerolinecolor = '#ffff',
                   zerolinewidth = 2,
                   gridcolor = 'ffff'),
      yaxis = list(zerolinecolor = '#ffff',
                   zerolinewidth = 2,
                   gridcolor = 'ffff'),
      plot_bgcolor='#e5ecf6', margin = 0.1, width = 900)
  return(fig)
}

stockssmi <- function(){
  getSymbols("^SSMI",
                     from = "2012-01-01",
                     to = Sys.Date())
  stock <- data.frame(SSMI$SSMI.Adjusted)
  stock$SSMI.Adjusted <- stock$SSMI.Adjusted/stock$SSMI.Adjusted[1]
  stock <- data.frame(stock,rownames(stock))
  colnames(stock) <- append('SSMI','date')
  
  smi <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
    add_trace(x = ~date, y = ~SSMI, name = 'SMI')%>%
    layout(showlegend = F)
  options(warn = -1)
  
  smi <- smi %>%
    layout(autosize = T,
      xaxis = list(zerolinecolor = '#ffff',
                   zerolinewidth = 2,
                   gridcolor = 'ffff'),
      yaxis = list(zerolinecolor = '#ffff',
                   zerolinewidth = 2,
                   gridcolor = 'ffff'),
      plot_bgcolor='#e5ecf6')
  return(smi)
}

pieall <- function(){
  df <- data.frame(Asset = c("Bitcoin","Gold", "Schweizer Bonds","SMI", "SP500", "US 10y Bonds", "USD/CHF Devisen"),
                   Wert = c(input$btc,input$gold,input$swissbonds,input$smi,input$sp500,input$us10,input$usdchf))
  
  fig <- df %>% plot_ly(labels = ~Asset, values = ~Wert)
  fig <- fig %>% add_pie(hole = 0.6)
  
  fig <- fig %>% layout(autosize = T,title = "",  showlegend = T,
                        xaxis = list(showgrid = F, zeroline = F, showticklabels = F),
                        yaxis = list(showgrid = F, zeroline = F, showticklabels = F))
  return(fig)
}

``` 
noahae
  • 1
  • 4
    This is a lot of code to ask someone to go though. It's easier to help if you provided a more minimal [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), Shiny specific tips here: https://github.com/rstudio/shiny/wiki/Creating-a-Reproducible-Example. Take out all code that's not essential to the problem. – MrFlick Apr 11 '22 at 19:43
  • Your `numericInput()` IDs may not be unique. – YBS Apr 11 '22 at 23:48

0 Answers0