График ggplot2, преобразованный в заговор, не отвечает В приложении Shiny - PullRequest
0 голосов
/ 02 мая 2018

Здравствуйте. Я создал блестящее приложение, которое создает барплот, но при попытке преобразовать его в плотно с ggplotly() оно не отвечает. Кто-нибудь знает, как сделать преобразование? Мои наборы данных находятся в форме таблицы данных, и я воссоздал их с tibble(). Ниже приведен минимальный пример моего кода. Я предполагаю, что может быть проблема с моим синтаксисом ggplot, но я не могу понять это.

##DATA TABLES
library(tibble)

id = c(1,2) 
fkAppUserid=c("ae95cd0e-06ea-4968-818a-e39db99580e1","7936202a-d295-4a93-aec8-4375fc760459")
fkAppSessionid=c("6e34b683-f978-42a0-b119-e77abf0372a6","3a0b8dac-7d12-4ceb-9cd4-0bcc9fb0b5e6")
fkAppQuestionid=c("cec559ca-165f-4273-a063-49628222cb15","cec559ca-165f-4273-a063-49628222cb15")
appAnswerStartDate=c("2017-10-10 08:11:26","2017-10-10 09:30:34")
date=c("2017-10-10","2017-10-10")
time=c("08:11:26","09:30:34")
skipped=c("f","f")
value=c("Ruben","Sjakie Stokvis")
appAnswer2 = tibble(id,fkAppUserid,fkAppSessionid,fkAppQuestionid,appAnswerStartDate,date,time,skipped,value)  


appQuestionid=c("003bc6ab-7305-490d-be2b-2a3267ce1eb0","0177cea1-6b5a-47bd-8512-2593f51c2ac4")
question=c("sadasdadadasdasdad","ddsfasfdff")
alias=c("verify-name","ask-health")
category=c("motivation","motivation")
isSub=c("t","f")
type=c("singleChoice","singleChoice")
properties=c("{answers: [{text: {en: That's correct, nl: Dat klopt}, value: true}, {text: {en: You got it all wrong, nl: Je hebt het helemaal verkeerd}, value: false}]}","{answers: [{text: {en: That's correct, nl: Dat klopt}, value: true}, {text: {en: You got it all wrong, nl: Je hebt het helemaal verkeerd}, value: false}]}")
appQuestion2=tibble(appQuestionid,question,alias,category,isSub,type,properties)

appSessionid=c("000171eb-e80d-425b-82c3-3390dbdb8957","0001de52-5d22-43a8-9180-1f044cdcfa0f")
appUserid=c("fcb92833-0005-4d93-8b2b-bb921a88bebd","0001de52-5d22-43a8-9180-1f044cdcfa0f")
appStartDate=c("2017-12-19 21:38:12","2017-11-21 11:20:08")
appSession2=tibble(appSessionid,appUserid,appStartDate)

appUserid=c("008edf2f-b268-41c0-b659-fa4d26607ccb","011211cf-b586-4328-867f-5bcf39aa81cb")
appRegistrationDate=c("2017-11-21 16:54:33","2018-02-27 07:36:20")
appDepartmentid=c("584cca4f-7bea-4ac5-bfd7-4af108617186","2d3d70a2-e1ff-4ff2-808d-dd775095f7eb")
appCompanyid=c("","")
appCompany=c("Danny en Annemarie","AppGevraagd.nl")
appDepartment=c("","")
fkOrganisationid=c("NULL","43")
fkTeamid=c("NULL","NULL")
appUser2=tibble(appUserid,appRegistrationDate,appDepartmentid,appCompanyid,appCompany,appDepartment,fkOrganisationid,fkTeamid)

APP

---
runtime: shiny
title: "insights"
output:
  flexdashboard::flex_dashboard:
    logo: 
    vertical_layout: scroll
    orientation: rows

---

<script defer src="https://use.fontawesome.com/releases/v5.0.9/js/all.js" integrity="sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl" crossorigin="anonymous"></script>

<style type="text/css">

th.dt-center, td.dt-center {
    text-align: center;
}

th, td {
  text-align: center;
}

tfoot {
    display: table-header-group;
}

g.xtick{
    background-color: #d5ecf8;
    font-family: Corbel;
}

.section.sidebar {
    background-color: #d5ecf8;
}

.chart-title{
    display: none; 
}

.navbar-inverse {
    background-color: #219BD2;
    border-color: #1967be;
}

h5{
    font-family: Corbel;
}

body {
    font-family: Corbel;
    font-style: normal;
    font-size: 15px;
}

.selectize-input { 
    font-family: Corbel;
}

.selectize-dropdown {
    font-family: Corbel;
}
</style>

```{r global, include=FALSE}
#Loading packages and setting options
library(magrittr)
library(ggplot2)
library(dplyr)
library(data.table)
library(lubridate)
library(corrplot)
assignInNamespace("cedta.override", c(data.table:::cedta.override,"rmarkdown"), "data.table")
library(RMySQL) 
library(extrafont)
library(shinyjs)
library(plotly)
Sys.setlocale("LC_TIME", "English")
    # load user data
    users <-fread("appUser2.csv")

    # load session data
    SessionData<-fread("appSession2.csv")
    SessionData <- SessionData[,c("appSessionId", "appUserId", "appStartDate")]
    temp <- SessionData

    # load question data
    QuestionData <- fread("appQuestion2.csv")
    QuestionData <- QuestionData[,c("appQuestionId", "alias")]

    # load answer data
    answers <- fread("appAnswer2.csv")


```


Inputs {.sidebar}  
=====================================
```{r}

    selectInput(
        "Bedrijf", multiple=TRUE,
        label = h5("Bedrijf"),
        ""
    )

    selectInput(
        "Afdeling", multiple=TRUE,
        label = h5("Afdeling"),
        ""
    )

    observe(priority=0, { #Function for observing choices of the filter
        updateSelectInput(
        session,
        "Bedrijf",
        choices=c("All",sort(unique(dataset()$appCompany))))

        updateSelectInput(
        session,
        "Afdeling",
        choices=sort(unique(dataset()$appDepartment)))
    })

    observeEvent(input$Bedrijf, priority=1, {

        updateSelectInput(
        session,
        "Afdeling",
        choices=unique(as.character(subs()$appDepartment)))
    })
```





Energie {data-icon="fa-bolt"}
=====================================

Row {data-height=500}
-----------------------------------------------------------------------

```{r}
enyData<-reactive({
    #load data
    names(answers)[names(answers)=="fkAppUserId"] <- "appUserId"

    answers_users <- merge(answers,users, by="appUserId")
    names(answers_users)[names(answers_users)=="fkAppQuestionId"] <- "appQuestionId"

    merge_questions <- merge(answers_users,QuestionData, by="appQuestionId",all=TRUE)
    merge_questions <- as.data.table(merge_questions)
    merge_questions$appCompany <- tolower(merge_questions$appCompany)
    merge_questions$appDepartment <- tolower(merge_questions$appDepartment)
    merge_questions$appCompany <- gsub("rkz", "rode kruis ziekenhuis", merge_questions$appCompany)
    merge_questions$appCompany[grep("rode kruis", merge_questions$appCompany)] <- "rode kruis ziekenhuis"

    #energy_level
    energy <- subset(merge_questions, alias %in% "ask-energy")

    ## select relevant columns
    enyData <- energy[,c("appUserId", "appCompany", "appDepartment", "appAnswerStartDate", "value")] 

    #sentiment
    sentiment <- subset(merge_questions, alias %in% "ask-how-are-you")

    ## select relevant columns
    senData <- sentiment[,c("appUserId", "appAnswerStartDate", "value")]

    # parse dates
    enyData$appAnswerStartDate <- strptime(enyData$appAnswerStartDate, format="%Y-%m-%d %H:%M:%S") %>% as.POSIXct

    # prepare energy values
    enyData$energy <- enyData$value
    enyData$value <- NULL

    # drop rows that havne "null" in value
    enyData <- enyData[enyData$energy!="null",]

    # prepare levels
    enyData$energy    <- factor(enyData$energy, c(2, 1, 0, -1, -2))

    ################################################################################
    ################################# PARSE DATES ##################################
    ################################################################################

    enyData$hour <- hour(enyData$appAnswerStartDate) + minute(enyData$appAnswerStartDate)/60
    enyData$day  <- weekdays(enyData$appAnswerStartDate, abbreviate=TRUE)
    enyData$day  <- factor(enyData$day, levels=c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))

    # set resolution
    res <- 1 # 2 = 30 minutes (how many measurements in one hour?)
    enyData$hour <- round(enyData$hour * res) / res
    enyData$hour[enyData$hour==0] <- 1
    enyData
})

eny_subs<-reactive({
     temp<-enyData()
        if(!is.null(input$Bedrijf)) {
            if(!"All"%in%input$Bedrijf) {    
                    temp<-filter(temp,appCompany%in%input$Bedrijf)
            } else {temp<-filter(temp,appCompany%in%unique(dataset()$appCompany))}

        }

        if(!is.null(input$Afdeling)){
                    temp<-filter(temp,appDepartment%in%input$Afdeling)
              }
       temp
})
cols_energy <- rev(c("#FFD6A4", "#F9BE69", "#F7A334", "#F19203", "#D67C05"))

#################################### HOURS #####################################


output$energy_hour<-renderPlot({
        # all levels
    xlab <- seq(1, 24, 1/res)
    xpos <- seq(1, 24*res, 1)
    tab  <- table(eny_subs()$energy, factor(eny_subs()$hour, levels=xlab))
    tab  <- prop.table(tab, margin=2)

   #barplot(tab, col=cols_energy, border="white", las=1, family="Corbel", ylab="aantal", #xlab="uur", legend=TRUE,
 #       main="energie per uur", ylim=range(pretty(c(0, colSums(tab))))
  #      )
    #grid(nx=0, ny=NULL)

tab2<-as.data.frame.matrix(tab) 
ggplot(tab2,aes(x=factor(eny_subs()$hour),y=eny_subs()$energy))+
  geom_bar()
})
plotOutput("energy_hour")

```

1 Ответ

0 голосов
/ 02 мая 2018

Вы должны указать свое имя пользователя и ключ API, как это:

Sys.setenv("plotly_username"="your_username")
Sys.setenv("plotly_api_key"="your_api_key")

Если у вас нет учетной записи Plotly, вы можете создать ее бесплатно. Больше информации здесь: https://plot.ly/r/getting-started/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...