EzDevInfo.com

dygraphs

Interactive visualizations of time series using JavaScript and the HTML canvas tag

How to use UTF-8 characters in dygraph title in R

Using Rstudio [Windows8], when I use the dygraph function to plot a time series, I have a problem when trying to use UTF-8 characters in the main title.

library(dygraphs)
dygraph(AirPassengers, main = "Título")

This results in a title: "T?tulo"

I have tried to convert "Título" to the utf-8 enconding, but it doesn't work.


Source: (StackOverflow)

Dygraph: how to clear the graph data and reload it?

My application has refresh functionality in which all the present data on the graph should get cleared and data should be loaded from starting. I don't want to destroy the dygraph and recreate it but just need to clear the existing data and plot from starting. What I tried is

g.rawdata_ = null; g.updateOptions({'file': g.rawdata_});

But it throws the error. If i set rawdata to 0 and then try to update, it doesn't clear off the data. Any suggestion on how to do this?


Source: (StackOverflow)

Advertisements

How can we make a pie chart using dygraph

I would like to create pie chart using dygraph library. On the main site http://dygraphs.com/, i could't find the way to create pie chart


Source: (StackOverflow)

Scatter type graph in Dygraphs?

How can I plot a scatter graph using dygraphs. Data would be line the following.

X axis might have 5-20 values (catagories) Y values might be 1-10 values per value on the x-axis

This is an example of what i need.

Is this possible in Dygraphs?

Thanks Michael


Source: (StackOverflow)

Dashboard in shinydashboard

I am using shinydashboard for the first time and it is brilliant. However I am stuck at an odd problem. I have the following code which is running on my browser. However when deployed on shinyapps.io it simply refuses to work.I have provided the code below. The dashboard is intended to do 3 things:
1. Visualize dependent variable
2.Automatically mark spikes with date dummies on graph with red vertical lines
3.See the independent variables and dummy variables selected

This is the link to the app in shinyapps.io http://rajarshibhadra.shinyapps.io/Test_Doubts

The code is as follows

ui.R
library(shiny)
library(shinydashboard)
library(dygraphs)
dashboardPage(
  dashboardHeader(title="Dashboard"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Dashboard",tabName="dashboard",icon=icon("dashboard"))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "dashboard",
              fluidRow(
                column(12,
                       box(title = "Plot Dependant", status = "primary", solidHeader = TRUE,
                           collapsible = TRUE,
                           dygraphOutput("final_plot",width = "100%", height = "300px"),width=8),
                       box(title="Model Specifications",status="warning",solidHeader= TRUE,
                           collapsible= TRUE,
                           uiOutput("mg"),width=4
                       )),
                column(12,
                       tabBox(title="Independants and Dummies",
                              tabPanel("Independants",verbatimTextOutput("modelvars")),
                              tabPanel("Dummies",verbatimTextOutput("modeldummies")),width=8
                       ),
                       box(title = "Inputs", status = "warning", solidHeader = TRUE,
                           collapsible = TRUE,
                           uiOutput("dependant"),
                           uiOutput("independant"),
                           uiOutput("dummies"),
                           sliderInput("spikes","Magnitude of strictness of crtiteria for spike",min=1,max=5,value=3,step=1),
                           sliderInput("dips","Magnitude of strictness of crtiteria for dips",min=1,max=5,value=3,step=1),width=4)

                ))

      )

    )
  ))


server.R

library(shiny)
library(stats)
library(dplyr)
library(dygraphs)

##
library(shinydashboard)
function(input, output) {

  raw_init<-data.frame(wek_end_fri=c("06Jul2012","13Jul2012","20Jul2012","27Jul2012","03Aug2012","06Jul2012","13Jul2012","20Jul2012","27Jul2012","03Aug2012"),
             Var1=c(468.9,507.1,447.1,477.1,452.6,883113.7,814778.0,780691.2,793416.6,833959.6),
             Var2=c(538672.6,628451.4,628451.4,628451.4,359115.8,54508.8,56036.1,57481.0,58510.0,59016.7),       
             MG= c("Cat1","Cat1","Cat1","Cat1","Cat1","Cat1","Cat1","Cat1","Cat1","Cat1","Cat2","Cat2","Cat2","Cat2","Cat2","Cat2","Cat2","Cat2","Cat2","Cat2")
             )


  #Select Category
  output$mg<-renderUI({
    selectInput("Category","Select Category",c("Cat1","Cat2"))
  })
  raw_init_filter<-reactive({
    filter(raw_init,MG == input$Category)
  })

  #Interpret Date
  raw_init_date<-reactive({
    mutate(raw_init_filter(),wek_end_fri=as.Date(wek_end_fri,"%d%b%Y"))
  })

  #Get variable Names
  Variable_list<-reactive({
    colnames(raw_init_date())
  })
  #Get potential dummy list
  Dummy_List<-reactive({
    raw_init_date()$wek_end_fri
  })
  #Load dependant
  output$dependant<-renderUI({
    selectInput("deplist","Select Dependant Variable",Variable_list(),selected="Var1")
  })
  #load independant
  output$independant<-renderUI({
    selectInput("indeplist","Select Independant Variable",Variable_list(),multiple=TRUE)
  })
  #Sepereate out Dependant
  dep<-reactive({
    raw_init_date()[input$deplist]
  })

  #Spike detection
  plot_data<-reactive({
    data.frame(Time=raw_init_date()$wek_end_fri,dep())
  })
  plot_data_mut<-reactive({
    f <- plot_data()
    colnames(f)[colnames(f)==input$deplist] <- "Volume"
    f
  })
  dep_vec<-reactive({
    as.vector(plot_data_mut()$Volume)
  })
  #Calculating mean
  dep_mean<-reactive({
    mean(dep_vec())
  })
  dep_sd<-reactive({
    sd(dep_vec())
  })
  transformed_column<-reactive({
    (dep_vec()-dep_mean())/dep_sd()
  })
  detected_index_spike<-reactive({
    which(transformed_column()>input$spikes/2)
  })
  detected_index_trough<-reactive({
    which(transformed_column()<(input$dips/(-2)))
  })
  detected_index<-reactive({
    c(detected_index_spike(),detected_index_trough())
  })
  detected_dates<-reactive({
    raw_init_date()$wek_end_fri[detected_index()]
  })

  output$dummies<-renderUI({
    validate(
      need(raw_init, 'Upload Data to see controls and results')
    )
    selectInput("dummies","Suggested Dummy Variable",as.character(Dummy_List()),selected=as.character(detected_dates()),multiple=TRUE)
  })
  indlist<-reactive({
    data.frame(Independant_Variables=input$indeplist)
  })
  output$modelvars<-renderPrint({
    indlist()
  })
  dumlist<-reactive({
    data.frame(Dummies=paste("Dummy_",as.character(format(as.Date(input$dummies,"%Y-%b-%d"),"%d%b%y")),sep=""))
  })
  output$modeldummies<-renderPrint({
    dumlist()
  })



  #-----------------------------------------------------------------------------------------#
  library(xts)
  plot_data_xts<-reactive({
    xts(dep(),order.by=as.Date(raw_init_filter()$wek_end_fri,"%d%b%Y"))
  })

  ##
  getDates <- reactive({
    as.character(input$dummies)
  })
  addEvent <- function(x,y) {
    dyEvent(
      dygraph=x,
      date=y,
      "", 
      labelLoc = "bottom",
      color = "red", 
      strokePattern = "dashed")
  }
  basePlot <- reactive({ 
    if (length(getDates()) < 1) {
      dygraph(
        plot_data_xts(),
        main="Initial Visualization and dummy detection") %>%
        dyAxis(
          "y", 
          label = "Volume") %>%
        dyOptions(
          axisLabelColor = "Black",
          digitsAfterDecimal = 2,
          drawGrid = FALSE)
    } else {
      dygraph(
        plot_data_xts(),
        main="Initial Visualization and dummy detection") %>%
        dyAxis(
          "y", 
          label = "Volume") %>%
        dyOptions(
          axisLabelColor = "Black",
          digitsAfterDecimal = 2,
          drawGrid = FALSE) %>%
        dyEvent(
          dygraph=.,
          date=getDates()[1],
          "", 
          labelLoc = "bottom",
          color = "red", 
          strokePattern = "dashed")
    }
  })
  ##

  output$final_plot <- renderDygraph({

    res <- basePlot()
    more_dates <- getDates()
    if (length(more_dates) < 2) {
      res
    } else {
      Reduce(function(i,z){
        i %>% addEvent(x=.,y=z)
      }, more_dates[-1], init=res)
    }

  })






}

Source: (StackOverflow)

Generate javascript file on the fly in asp.net mvc

Friends,

I am trying to use DyGraph in my application. Please look at the code below -

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
    <title>crosshairs</title>

    <script type="text/javascript" src="dygraph-combined.js"></script>

    <script type="text/javascript" src="data.js"></script>
  </head>

The code uses data.js file containing function to get some static data. I want data.js to be generated using a controller method so that it will generate data using database.

Can anybody help me out to resolve this issue.

Thanks for sharing your valuable time.


Source: (StackOverflow)

Dygraph's %>% replacing Dplyr's

I'm writing a package that imports shiny, dygraphs and shiny. However, whenever I'm Build & Load the package, there's always a warning, replacing previous imports by 'dygraphs::%>%' when loading mypkg.

I've tried change the order in DESCRIPTION, but it doesn't work. Also, the package uses a lot of dplyr functions as well as dygraphs', so I can't just say importFrom, otherwise it will be a long list. Therefore, is there any way to not import dygraphs::%>% or dplyr::%>% into my package? Or is there any other way to solve this warning? Thanks!


Source: (StackOverflow)

d3 bar chart with range selector in x-axis (like dygraphs)

Is it possible to generate a bar chart in d3 and use similar tool or feature like the one in dygraphs (this) for range Selector? I want to zoom in and out for the time on x-axis.

Thanks!


Source: (StackOverflow)

Decreasing the stepsize of Y Axis

Is there a way to set the YSTEP of the graph?

We are trying to show a chart with the below data

g = new Dygraph(
    document.getElementById("graph"),
            [
                 [1,10,10],
                 [2,20.11,20],
                 **[3,10.111,10]**,
                 [4,20,20]],
            {labels: [ "x", "A", "B" ]});

but the out put is rounded with 0.01, and we are getting as

g = new Dygraph(
    document.getElementById("graph"),
            [
                 [1,10,10],
                 [2,20.11,20],
                 **[3,10.11,10]**,
                 [4,20,20]],
            {labels: [ "x", "A", "B" ]});

How to correct it?


Source: (StackOverflow)

Dygraphs in R does not show color when viewing in browser

I am using "dygraphs" package in R to draw a bar chart and assign green color to all bars. The thing is totally fine when I display the chart in R, but all bars turn black when I try to display them in a web browser. Here is the code (a clip of Javascript is included because Google says I can use that to draw bar charts using dygraph):

library(xts)
library(dygraphs)
library(lubridate)
library(dplyr)

df  <- data.frame(date = as.Date(13800:13810, origin = "1970-01-01"),
                  n    = 1:11)

graph_data <- xts(x = 1:10, order.by = as.Date(13801:13810, origin = "1970-01-01"))

dygraph(graph_data) %>%
    dyOptions(useDataTimezone = TRUE,
              colors = c("008000"),
              plotter = 
                  "function barChartPlotter(e) {
            var ctx = e.drawingContext;
            var points = e.points;
            var y_bottom = e.dygraph.toDomYCoord(0);  

            var bar_width = 1/2 * (points[1].canvasx - points[0].canvasx);
            ctx.fillStyle = e.color;

            for (var i = 0; i < points.length; i++) {
            var p = points[i];
            var center_x = p.canvasx;  // center of the bar

            ctx.fillRect(center_x - bar_width / 2, p.canvasy,
            bar_width, y_bottom - p.canvasy);
            ctx.strokeRect(center_x - bar_width / 2, p.canvasy,
            bar_width, y_bottom - p.canvasy);
            }
            }")

I might have to use dygraphs to draw bars because it is fast in drawing thousands of bars...

Any help is appreciated!


Source: (StackOverflow)

Change source/content of a div dynamically with long blocks including scripts

I have seen lots of questions & answers regarding similar issues, but I have not found answer for this particular case.

I have a <div> in the webpage where I show dynamically data into a graphic, it requires javascript into the <div> (using dygraph library). I want implement a checkbox to change the content of the <div> between the graphic code and the code to show a live-webcam connection, which requires script too.

I have tried with innerHTML and jQuery function based on examples I have found, but all of them are referred to a very simple HTML changes without script content, the more complicated I have found is how to change a picture into the <div> content. I have read that <div> doesn't support src property, other forum says yes, in my case it has not worked. The library div-src.js, doesn't work for this case too.

The other attempt was with <iframe> tag it has worked but page doesn't work properly and goes unstable, specially the websocket connection. Eclipse shows a warning saying "unknown tag" and I have read that <iframe> is obsolete in HTML5.

I would like to perform this with jQuery but until know without success.

What is the best method to insert dynamically into a <div> long blocks of HTML code with script, with calls to js libraries?.

<input type="radio" name="radiobutton" value="graph" onClick="changeDivContent()">
<input type="radio" name="radiobutton" value="video" onClick="changeDivContent()">

<div id="graph-video">
 --- Block with HTML, nesting divs and javascript ---
</div>

Note: With jQuery I have tried to use the .load function:

$( "#graph-video" ).load( "video.jsp" );
$( "#graph-video" ).load( "graphic.jsp" );

with the result: code for the graphic cause malfunction and websocket close.


Source: (StackOverflow)

How to Render Dygraph in iPython Notebook?

I would eventually like to pass data from python data structures to Javascript elements that will render it in a Dygraphs graph within an iPython Notebook.

I am new to using notebooks, especially the javascript/nobebook interaction. I have the latest Dygraphs library saved locally on my machine. At the very least, I would like to be able to render a sample Dygraphs plot in the notebook using that library.

See the notebook below. I am trying to execute the simple Dygraphs example code, using the library provided here: http://dygraphs.com/1.0.1/dygraph-combined.js

However, I cannot seem to get anything to render. Is this the proper way to embed/call libraries and then run javascript from within a notebook?

notebook

Eventually I would like to generate JSON from Pandas DataFrames and use that data as Dygraphs input.


Source: (StackOverflow)

Highlight Closest Series - but only show X/Y of highlighted series?

I'm trying to adapt my graph to behave like the last 2 graphs on this page: http://dygraphs.com/tests/series-highlight.html where on mouse-hover, it only displays the X/Y coordinates of the specific highlighted series, not ALL of the coordinates for that X value.

I can't seem to discern where in the javascript it specifies that, and it seems that all 4 of those graphs are set up the same, but behave differently.

My code currently looks like this, and works well for highlighting the closest series, but is just too cluttered with ALL the label points.

<script type="text/javascript">
g = new Dygraph(

// containing div
document.getElementById("graphdiv"),

// CSV or path to a CSV file.
<?php echo $chartDataString; ?>,
{
    title: 'Total Cycles',
    ylabel: 'Portfolio ($)',
    xlabel: 'Year',
    labelsDivStyles: { 'textAlign': 'right' },
    digitsAfterDecimal: 0,
    axes: {
        y: {
                labelsKMB: true,
        },
    },
    showLabelsOnHighlight: false,
    highlightCircleSize: 2,
    strokeWidth: 1,
    strokeBorderWidth: 1,
    highlightSeriesOpts: {
      strokeWidth: 3,
      strokeBorderWidth: 1,
      highlightCircleSize: 5,
    },
}

 );

Any ideas? I'm fairly new to javascript, and just can't quite get a handle on whats going on in the example.


Source: (StackOverflow)

How to restrict the zoom?

I would like to restrict the zoom in a way, that its not possible to zoom deeper than a certain value. E.g. my data dates from days / months down to 15 minutes, so the smallest value I would like to show (and therefore give the user the ability to zoom only this far) would be like showing 4-5 values of those 15minutes intervalls.

I have found the ticker-possibility in another thread, but thats not helping because it doesn´t restrict the ability to zoom. Is there a builtin method that can help me or another way to restrict the zoomfactor ?


Source: (StackOverflow)

Hiding Label in Dygraph.js

I am drawing a line at some certain point but what i want is that either i can hide the label for that particular line in the legend or i can change the value of that line in the legend

Note: The value at which the line is drawn and the value in the legend should be the same.Its one of my requirements

How is it possible ? Any help would be greatly appreciated .

Thanks


Source: (StackOverflow)