99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀用R做一個靈活的時間序列數(shù)據(jù)可視化工具
用R做一個靈活的時間序列數(shù)據(jù)可視化工具
2016-10-15
收藏

用R做一個靈活的時間序列數(shù)據(jù)可視化工具

一、數(shù)據(jù)可視化的煩惱

數(shù)據(jù)分析師經(jīng)常需要看數(shù)據(jù)。通常而言,數(shù)據(jù)或存放在MySQL數(shù)據(jù)庫,或存放在Hadoop集群,或存放在阿里云的ODPS上。分析師根據(jù)業(yè)務(wù)需求寫SQL語句從數(shù)據(jù)平臺上提取出需要的數(shù)據(jù),隨后就面臨著本文要重點討論的怎么對數(shù)據(jù)可視化的難題。

用R做一個靈活的時間序列<a href='/map/shujukeshihua/' style='color:#000;font-size:inherit;'>數(shù)據(jù)可視化</a>工具

對于一個固定的需求,通常需要觀察多組數(shù)據(jù)。普通一點的分析師,可能是拷貝出一組數(shù)據(jù),貼到Excel里,繪個圖看一下,然后拷貝下一組數(shù)據(jù);高級一點的分析師,可能是用R寫好一段代碼,然后修改分組的變量取值重復(fù)運行代碼來觀察多組數(shù)據(jù)。我在工作中動輒需要觀察一百組數(shù)據(jù),上述兩種方法仍然不夠好用,最好的方法是我鼠標(biāo)點擊一百次,每點擊一次產(chǎn)生一幅圖。

更可惡的是,每來一個新需求,不論是Excel還是R都得根據(jù)新需求定制化一遍操作或一套代碼。

于是某一天,我實在忍不了,就嘗試做了一個工具,將SQL寫完后的數(shù)據(jù)可視化工作給工程化了。

這個工具首先支持select查詢語句,執(zhí)行成功后會顯示執(zhí)行結(jié)果,同時提供一個設(shè)置面板,讓用戶選擇數(shù)據(jù)分組字段、x軸字段、y軸字段,然后生成分組結(jié)果,每點擊一個結(jié)果,生成該分組數(shù)據(jù)的圖。目前該工具只支持時間序列數(shù)據(jù),能夠繪制點圖和線圖。

二、技術(shù)方案

Shiny:R的Web開發(fā)框架,讓數(shù)據(jù)分析師能夠?qū)⒎治龀晒焖俎D(zhuǎn)化為交互式網(wǎng)頁分享給別人。

它跟通常我們了解的其他框架不一樣:其他框架一般都是前后端分離,后端提供json,前端根據(jù)json繪圖繪表,需要若干個程序員協(xié)同開發(fā)完成。然而這種可視化的小工具往往是得不到研發(fā)資源的支持,只能本數(shù)據(jù)分析師一人操刀前后端全包。

當(dāng)一個項目以數(shù)據(jù)計算和可視化為核心,只投入數(shù)據(jù)分析師一個人,要求快速實現(xiàn)效果,對執(zhí)行效率和負(fù)載無要求,那么shiny無疑是一個非常誘人的方案。

三、代碼

  1. #########################
  2. # 時間序列數(shù)據(jù)可視化工具
  3. # @author: shuiping.chen@alibaba-inc.com
  4. # @date: 2016-07-10
  5. #########################

  6. library(shiny)
  7. library(shinyjs)
  8. library(DT)
  9. library(dplyr)
  10. library(tidyr)
  11. library(stringr)
  12. library(ggplot2)
  13. library(scales)
  14. library(plotly)

  15. run.sql <- function(sql, debug=FALSE) {  if(debug==FALSE){
  16.     df <- XXXXX # 自行定義函數(shù),根據(jù)數(shù)據(jù)存儲位置,執(zhí)行SQL語句
  17.   }  else{
  18.     # 測試數(shù)據(jù)    group_id <- rep(1, nrow(economics))    dt <- paste(as.character(economics$date), "00:00:00")    df <- cbind(group_id, dt, economics)
  19.   }  return(df)
  20. }ui <- fluidPage(  useShinyjs(),  titlePanel("時間序列數(shù)據(jù)可視化工具"),
  21.   # 第一部分:SQL命令提交界面  div(id="download",      fluidRow(        column(12,               textOutput(outputId="download_info")
  22.         )
  23.       ),      fluidRow(        column(12,
  24.                HTML(                 paste('',
  25.                        "select * from xxxx limit 1000;",
  26.                        '')
  27.                )
  28.         )
  29.       ),
  30.       fluidRow(
  31.         column(12,
  32.                actionButton(inputId="refresh_button", label="加載數(shù)據(jù)", icon=icon("submit")
  33.                )
  34.         )
  35.       )
  36.   ),


  37.   shinyjs::hidden(
  38.     div(id="table",
  39.         # 第二部分:SQL命令執(zhí)行結(jié)果顯示
  40.         hr(),
  41.         dataTableOutput(outputId="sql_tab"),

  42.         # 第三部分:可視化規(guī)則設(shè)置
  43.         hr(),
  44.         textOutput(outputId="tab_button_message"),
  45.         sidebarLayout(
  46.           div(id="table_tool",
  47.               sidebarPanel(
  48.                 selectInput(inputId="group_fields", label="繪圖分組字段", choices=NULL, selected=NULL, multiple=TRUE),
  49.                 selectInput(inputId="x_field", label="設(shè)置x軸字段,必須是日期時間", choices=NULL, selected=NULL, multiple=FALSE),
  50.                 selectInput(inputId="y_line_fields", label="設(shè)置y軸線圖字段", choices=NULL, selected=NULL, multiple=TRUE),
  51.                 selectInput(inputId="y_point_fields", label="設(shè)置y軸點圖字段", choices=NULL, selected=NULL, multiple=TRUE),
  52.                 selectInput(inputId="group_shape_field", label="設(shè)置點圖形狀字段", choices=NULL, selected=NULL, multiple=FALSE),
  53.                 actionButton(inputId="tab_button", label="顯示分組表格", icon=icon("submit")),
  54.                 width=3
  55.               )
  56.           ),
  57.           div(id="group_content",
  58.               mainPanel(dataTableOutput(outputId="group_tab"),
  59.                         width=9
  60.               )
  61.           )
  62.         )
  63.         )
  64.   ),

  65.   # 第四部分:可視化圖形
  66.   shinyjs::hidden(
  67.     div(id = "plot",
  68.         hr(),
  69.         plotlyOutput(outputId="case_viewer", height="600px")
  70.     )
  71.   )
  72.   )

  73. server <- function(input, output, session) {  observe({
  74.     # 檢查SQL輸入框    if(is.null(input$sql_cmd) | input$sql_cmd == "") {      shinyjs::disable("refresh_button")
  75.     }    else{      shinyjs::enable("refresh_button")
  76.     }
  77.     # 檢查可視化規(guī)則設(shè)置    if (input$x_field == "" | (is.null(input$y_line_fields) & is.null(input$y_point_fields)) | is.null(input$group_fields)) {      shinyjs::disable("tab_button")
  78.     } else {      shinyjs::enable("tab_button")
  79.     }
  80.   })

  81.   # 執(zhí)行SQL命令獲取數(shù)據(jù)  sql_data <- eventReactive(input$refresh_button, {    cat(file=stderr(), "#### event log ####: refresh button clicked\n")    shinyjs::disable("refresh_button")    shinyjs::hide(id = "table", anim = TRUE)    shinyjs::hide(id = "plot", anim = TRUE)    res <- run.sql(input$sql_cmd, debug=TRUE)
  82.     updateSelectInput(session, inputId="group_fields", choices=colnames(res))
  83.     updateSelectInput(session, inputId="x_field", choices=colnames(res))
  84.     updateSelectInput(session, inputId="y_line_fields", choices=colnames(res))
  85.     updateSelectInput(session, inputId="y_point_fields", choices=colnames(res))
  86.     updateSelectInput(session, inputId="group_shape_field", choices=c("無",colnames(res)), selected="無")    shinyjs::enable("refresh_button")    shinyjs::show(id = "table", anim = TRUE)    shinyjs::hide(id = "group_content", anim = FALSE)    return(res)
  87.   })

  88.   # SQL命令執(zhí)行狀態(tài)  output$download_info <- renderText({    if(input$refresh_button == 0){      message <- "請敲入SQL select查詢語句,點擊按鈕提交"
  89.     }    else{      message <- isolate({paste0("表格下載成功!總行數(shù)",  nrow(sql_data()), ",總列數(shù)", ncol(sql_data()), ",更新時間是", as.character(lubridate::now(), format="%Y-%m-%d %H:%M:%S"))
  90.       })
  91.     }    message
  92.   })

  93.   # 顯示SQL執(zhí)行結(jié)果  output$sql_tab <- DT::renderDataTable({    datatable(sql_data(), filter='top', selection='single')
  94.   })

  95.   # 獲取繪圖分組結(jié)果  group_data <- eventReactive(input$tab_button, {    cat(file=stderr(), "#### event log ####: tab button clicked\n")    res <- sql_data() %>%
  96.       select(one_of(input$group_fields)) %>%
  97.       distinct()
  98.     shinyjs::show(id="group_content", anim=TRUE)
  99.     return(res)
  100.   })

  101.   output$tab_button_message <- renderText({    if(input$tab_button == 0) {      message <- "請在下方左側(cè)設(shè)置數(shù)據(jù)可視化規(guī)則;
  102.                  點擊按鈕后,下方右側(cè)將以表格顯示數(shù)據(jù)分組結(jié)果;
  103.                點擊表格的一行,將在下方繪制該行所指分組數(shù)據(jù)的圖形"
  104.     }    else {      message <- isolate({paste0("繪圖分組數(shù)",  nrow(group_data()), ",更新時間是", as.character(lubridate::now(), format="%Y-%m-%d %H:%M:%S"))
  105.       })
  106.     }    message
  107.   })

  108.   # 顯示繪圖分組結(jié)果  output$group_tab <- DT::renderDataTable({    datatable(group_data(), filter='top', selection='single')
  109.   })

  110.   # 顯示繪圖  observeEvent(input$group_tab_rows_selected, {    cat(file=stderr(), paste0("#### event log ####: group table row ", input$group_tab_rows_selected, " clicked\n"))    output$case_viewer <- renderPlotly({      s <- input$group_tab_rows_selected
  111.       cat(file=stderr(), "#### event log ####: table row", s, "clicked\n")      p <- ggplot()      filter_str <- isolate({str_c(group_data()[s, input$group_fields], collapse="_")}) # 使用_以配合unite方法      target_plot_data <- sql_data() %>%
  112.         unite_("new_var", input$group_fields, remove=FALSE) %>%
  113.         filter(new_var==filter_str)

  114.       if(length(input$y_line_fields) > 0) {
  115.         target_plot_data$dt <- lubridate::ymd_hms(target_plot_data[,input$x_field], tz="UTC-8")        line_df <- target_plot_data %>%
  116.           tidyr::gather(col_name, thresh, one_of(input$y_line_fields)) %>%
  117.           dplyr::mutate(thresh=as.numeric(thresh))
  118.         p <- p + geom_line(data=line_df, aes(x=dt,y=thresh,color=col_name))
  119.       }      if(length(input$y_point_fields) > 0) {
  120.         target_plot_data$dt <- lubridate::ymd_hms(target_plot_data[,input$x_field], tz="UTC-8")        point_df <- target_plot_data %>%
  121.           tidyr::gather(col_name, thresh, one_of(input$y_point_fields)) %>%
  122.           dplyr::mutate(thresh=as.numeric(thresh))
  123.         if(input$group_shape_field != "無") {
  124.           point_df[, input$group_shape_field] <- as.factor(point_df[, input$group_shape_field])          p <- p + geom_point(data=point_df, aes_string(x="dt",y="thresh",color="col_name", shape=input$group_shape_field))
  125.         }        else{          p <- p + geom_point(data=point_df, aes(x=dt,y=thresh,color=col_name))
  126.         }
  127.       }      p <- p
  128.       ggplotly(p)
  129.     })    shinyjs::show("plot", anim = TRUE)
  130.   })
  131. }shinyApp(ui=ui, server=server)

注:為了讓用戶明白工具的使用方法,代碼采用shinyjs在適當(dāng)?shù)臅r機(jī)隱藏/顯示對應(yīng)的組件;在eventReactive事件驅(qū)動的計算中,需要保證至少一個依賴與該reactive的組件處于顯示狀態(tài),否則無法觸發(fā)計算,observeEvent不存在此問題。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }