+ Reply to Thread
Results 1 to 12 of 12

JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

Hybrid View

  1. #1
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Question JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    Code below submitted by user Kyle123, makes for a seamless word cloud integration within excel. I am hoping to make a few tweaks. Specifically I'd like to find a way to change the colors of my 5 top occurring words (i.e. make the biggest boldest tags appear red as they represent a high occurrence of injuries for my specific use. I'd also like to be able to run off of whatever portion of a column I currently have selected, rather than statically referencing say A1:A50.

    The second goal should be easy within the vba, but I'm guessing the first change would have to reside within http://visapi-gadgets.googlecode.com...rdcloud/wc.css, http://visapi-gadgets.googlecode.com...ordcloud/wc.js, or text/javascript"" src=""http://www.google.com/jsapi""></script>. My apologies, I'm not very familiar with google visualizations or jquery. And thank you Kyle123 for what seems to be one of the best inclusions of a word cloud generating tool within excel.

    Sub test()
    
     Dim CloudData As Range
     
    'WordCloud Sheet1.Range("A1:A50")
    Selection.Name = "CloudData"
    
    
    WordCloud Sheet1.Range("CloudData")
    End Sub
    
    
    Sub WordCloud(rngInput As Range)
    Dim wbString As String
    Dim myFile As String
    Dim rngVar As Variant
    Dim fnum As Integer
    Dim i As Integer
    
    rngVar = Application.Transpose(rngInput.Value)
    
    
    wbString = "<html>" & vbCr
    wbString = wbString & "  <head>"
    wbString = wbString & "    <link rel=""stylesheet"" type=""text/css"" href=""http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.css""></script>" & vbCr
    wbString = wbString & "    <script type=""text/javascript"" src=""http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.js""></script>" & vbCr
    wbString = wbString & "    <script type=""text/javascript"" src=""http://www.google.com/jsapi""></script>" & vbCr
    wbString = wbString & "  </head>" & vbCr
    wbString = wbString & "  <body>" & vbCr
    wbString = wbString & "    <div id=""wcdiv""></div>" & vbCr
    wbString = wbString & "    <script type=""text/javascript"">" & vbCr
    wbString = wbString & "      google.load('visualization', '1');" & vbCr
    wbString = wbString & "      google.setOnLoadCallback(draw);" & vbCr
    wbString = wbString & "      function draw() {" & vbCr
    wbString = wbString & "        var data = new google.visualization.DataTable();" & vbCr
    wbString = wbString & "        data.addColumn('string', 'Text1');" & vbCr
    wbString = wbString & "        data.addRows(" & UBound(rngVar) & ");" & vbCr
    
    For i = 1 To UBound(rngVar)
        wbString = wbString & "        data.setCell(" & i - 1 & ", 0,'" & rngVar(i) & "');" & vbCr
    Next i
    
    wbString = wbString & "        var outputDiv = document.getElementById('wcdiv');" & vbCr
    wbString = wbString & "        var wc = new WordCloud(outputDiv);" & vbCr
    wbString = wbString & "        wc.draw(data, null);" & vbCr
    wbString = wbString & "      }" & vbCr
    wbString = wbString & "    </script>" & vbCr
    wbString = wbString & "  </body>" & vbCr
    wbString = wbString & "</html>"
    
    
    myFile = ThisWorkbook.Path & "\WordCloud.htm"
    fnum = FreeFile()
    Open myFile For Output As fnum
    Print #fnum, wbString
    Close #fnum
    
    
    With Cloud.WebBrowser1
        .Silent = True
        .Navigate (myFile)
        Do
            DoEvents
        Loop Until .ReadyState = READYSTATE_COMPLETE
        .Document.body.Scroll = "no"
    End With
    
    
    End Sub

  2. #2
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    This will allow you to set the colours, I have removed the external style sheet so it is easy to change the colours/font sizes.

    To change the colours, you need to adjust the # numbers in red below, they are listed in ascending order do the last is the most frequently occurring word and the first is the least occurring

    Sub WordCloud(rngInput As Range)
    Dim wbString As String
    Dim myFile As String
    Dim rngVar As Variant
    Dim fnum As Integer
    Dim i As Integer
    
    rngVar = Application.Transpose(rngInput.Value)
    
    
    wbString = "<html>" & vbCr
    wbString = wbString & "  <head>"
    wbString = wbString & "     <style type=""text/css"">" & vbCr
    wbString = wbString & "     .word-cloud {font-family: arial; font-size: 10px; }" & vbCr
    wbString = wbString & "     .word-cloud-1 {font-size: 10px; color: #acc1f3; }" & vbCr
    wbString = wbString & "     .word-cloud-2 {font-size: 14px; color: #86a0dc; }" & vbCr
    wbString = wbString & "     .word-cloud-3 {font-size: 18px; color: #607ec5; }" & vbCr
    wbString = wbString & "     .word-cloud-4 {font-size: 22px; color: #264ca2; }" & vbCr
    wbString = wbString & "     .word-cloud-5 {font-size: 26px; color: #133b97; }" & vbCr
    wbString = wbString & "     .word-cloud-6 {font-size: 32px; color: #002a8b; }" & vbCr
    wbString = wbString & "     .word-cloud-7 {font-size: 36px; color: #071a41; }" & vbCr
    wbString = wbString & "     .word-cloud-8 {font-size: 40px; color: #081122; }" & vbCr
    wbString = wbString & "     .word-cloud-9 {font-size: 44px; color: #000000; }" & vbCr
    wbString = wbString & "     </style>" & vbCr
    wbString = wbString & "    <script type=""text/javascript"" src=""http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.js""></script>" & vbCr
    wbString = wbString & "    <script type=""text/javascript"" src=""http://www.google.com/jsapi""></script>" & vbCr
    wbString = wbString & "  </head>" & vbCr
    wbString = wbString & "  <body>" & vbCr
    wbString = wbString & "    <div id=""wcdiv""></div>" & vbCr
    wbString = wbString & "    <script type=""text/javascript"">" & vbCr
    wbString = wbString & "      google.load('visualization', '1');" & vbCr
    wbString = wbString & "      google.setOnLoadCallback(draw);" & vbCr
    wbString = wbString & "      function draw() {" & vbCr
    wbString = wbString & "        var data = new google.visualization.DataTable();" & vbCr
    wbString = wbString & "        data.addColumn('string', 'Text1');" & vbCr
    wbString = wbString & "        data.addRows(" & UBound(rngVar) & ");" & vbCr
    
    For i = 1 To UBound(rngVar)
        wbString = wbString & "        data.setCell(" & i - 1 & ", 0,'" & rngVar(i) & "');" & vbCr
    Next i
    
    wbString = wbString & "        var outputDiv = document.getElementById('wcdiv');" & vbCr
    wbString = wbString & "        var wc = new WordCloud(outputDiv);" & vbCr
    wbString = wbString & "        wc.draw(data, null);" & vbCr
    wbString = wbString & "      }" & vbCr
    wbString = wbString & "    </script>" & vbCr
    wbString = wbString & "  </body>" & vbCr
    wbString = wbString & "</html>"
    
    
    myFile = ThisWorkbook.Path & "\WordCloud.htm"
    fnum = FreeFile()
    Open myFile For Output As fnum
    Print #fnum, wbString
    Close #fnum
    
    
    With Sheet1.WebBrowser1
        .Silent = True
        .Navigate (myFile)
        Do
            DoEvents
        Loop Until .ReadyState = READYSTATE_COMPLETE
        .Document.body.Scroll = "no"
    End With
    
    
    End Sub
    For the other part, you just need:

    sub test()
    WordCloud Selection
    End Sub
    Last edited by Kyle123; 12-19-2011 at 01:12 PM.

  3. #3
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    OK that should work for changing the colors then. Another question I had forgot about. Although I couldn't get your advised change to work for running off the selection.

    I moved the WebBrowser control to another sheet called "Cloud." I really wish I could tweak the code so that 1) I could run it any time off of a selected single column chunk of data i.e. highlight and say run and it will generate the new cloud based on the currently selected data. 2) that it displays this cloud on a different sheet than the worksheet containing all the data (I have multiple columns of data and it would be nicer to have the cloud appear on a separate worksheet), however the "With Cloud.WebBrowser1" I believe is fouling it up.

    With Cloud.WebBrowser1
        .Silent = True
        .Navigate (myFile)
        Do
            DoEvents
        Loop Until .ReadyState = READYSTATE_COMPLETE
        .Document.body.Scroll = "no"
    End With

  4. #4
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    You need:

    With Sheets("Cloud").WebBrowser1
        .Silent = True
        .Navigate (myFile)
        Do
            DoEvents
        Loop Until .ReadyState = READYSTATE_COMPLETE
        .Document.body.Scroll = "no"
    End With
    To run it from a selection

    Select the data, click run macro: MakeVis

    the code for the macro would be:
    Public Sub MakeVis()
    WordCloud Selection
    End sub

  5. #5
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    Thank you Kyle,

    Changing it to With Sheets("Cloud").WebBrowser1 seemed to take care of displaying it on a separate worksheet, also made my test code Public. To add any additional stop words I would somehow have to get into the referenced sites I presume?

  6. #6
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    Kyle and others,

    I have a similar problem I'm experiencing with another piece of tag cloud generating code. My plan is to use Kyle's or something like it for the customer when they have internet available and another one that will work (albeit not as beautifully) when internet isn't available and display both on a sheet called Cloud in sort of a dashboard type presentation. One issue I'm having with this code is I've been unable to successfully display the cloud on the cloud worksheet (sounding similar?). I had a cell on the cloud worksheet that had been formatted for the cloud to appear nicely (merged multiple cells together for one bigger one, with wrapped text, and a thick border). I have a little message which asks where you'd like to place the tag cloud since I was fiddling around a lot to see what it would and would not accept. Low and behold it will only accept a cell on the FreqTable worksheet (which is created to place the pivot table on). Is there any way so that I could get this to display on the same "Cloud" worksheet which now has the tag cloud from Kyle's code?

    Sub DoAll()
        
        Dim CloudData As Range
        
        On Error Resume Next
        
        'Asks user to specify which column of data they wish to summarize
        Set CloudData = Application.InputBox("Please select a range with the incident information you wish to summarize.", _
                                                  "Specify Incident Information", Selection.Address, , , , , 8)
    
    'Sub MakeTable()
    Dim Pt As PivotTable
    Dim strField As String
        
        'Pass heading to a String variable
        '*Need to make edit here most likely with some sort of if to use the first row heading
        'if selected data does not include this. i.e. if selected range starts with second row
        'or after.*
        
        'strField = Selection.Cells(1, 1).Text
        strField = CloudData.Cells(1, 1).Text
        
        'Name the list range not using the xlDown because there exists
        'the possibility of blanks in the column data.
        
        'Range(Selection, Selection.End(xlDown)).Name = "Items"
        CloudData.Name = "Items"
           
        'Create the Pivot Table based off our named list range.
        'TableDestination:="" will force it onto a new sheet
        
         ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
             SourceData:="=Items").CreatePivotTable TableDestination:="", _
                 TableName:="ItemList"
                    
        'Set a Pivot Table variable to our new Pivot Table
        Set Pt = ActiveSheet.PivotTables("ItemList")
        
        'Place the Pivot Table to start from A1 on the new sheet
        ActiveSheet.PivotTableWizard TableDestination:=Cells(1, 1)
            
        'Move the list heading to the Row Field
        Pt.AddFields RowFields:=strField
        
        'Move the list heading to the Data Field
        Pt.PivotFields(strField).Orientation = xlDataField
    
    ActiveSheet.Name = "FreqTable"
    
    'Sorts frequency table descending. *has stopped working since I started tweaking this code I found
    '    With Range("A1", Cells(Rows.Count, 2).End(xlUp)).Resize(, 2)
    '        .Sort .Cells(1, 2), xlDescending
    '    End With
    
    Call CreateCloud
    
    End Sub
    
    Sub CreateCloud()
    ' this subroutine creates a tag cloud based on the list format tagname, tag importance
    ' the tag importance can have any value, it will be normalized to a value between 8 and 20
    
    On Error GoTo tackle_this
    
    Range("A1:B1").Select
        Range(Selection, Selection.End(xlDown)).Select
    
    Dim size As Integer
    
    size = Selection.Count / 2
    
    Dim tags() As String
    Dim importance()
    
    ReDim tags(1 To size) As String
    ReDim importance(1 To size)
    
    Dim minImp As Integer
    Dim maxImp As Integer
    
    cntr = 1
    i = 1
    
    For Each cell In Excel.Selection
    
    'If counter / 2 returns a remainder of 1 i.e. it's a word column then print that "tag"
    '
        If cntr Mod 2 = 1 Then
            taglist = taglist & cell.Value & ", "
            tags(i) = cell.Value
        
    'Otherwise (remainder of 0) it must be a frequency count. Set importance(i) to that
    'frequency count and set max and min importance (frequency) accordingly
        Else
            importance(i) = Val(cell.Value)
            If importance(i) > maxImp Then
                maxImp = importance(i)
            End If
            If importance(i) < minImp Then
                minImp = importance(i)
            End If
            i = i + 1
        End If
        cntr = cntr + 1
    Next cell
    
    'Paste values in cell G1
    'Range("G1").Select
    
    'Ask user to select which cell they would like to place the tag cloud in
    Set CloudCell = Application.InputBox("Please select the cell where you'd like to place the word cloud.", _
                                                  "Specify Word Cloud Destination", Selection.Address, , , , , 8)
    CloudCell.Select
    
    'Sets active cell value to 'taglist' and cell fonts to size 8.
    ActiveCell.Value = taglist
    ActiveCell.Font.size = 8
    
    'Starting at first character slot within the cell
    strt = 1
    
    'Starting at tag 1 to however many tags are contained in the frequency table
    For i = 1 To size
    
    'With active cell start changing font size of characters. Applies formatting to
    'the appropriate number of characters based on the length of the word (Len(tags(i)).
    '*To Change Color must somehow adjust the .ColorIndex portion
    
        With ActiveCell.Characters(Start:=strt, Length:=Len(tags(i))).Font
            .size = 6 + Math.Round((importance(i) - minImp) / (maxImp - minImp) * 14, 0)
            .Strikethrough = False
            .Superscript = False
            .Subscript = False
            .OutlineFont = False
            .Shadow = False
            .Underline = xlUnderlineStyleNone
            .ColorIndex = xlAutomatic
        End With
        strt = strt + Len(tags(i)) + 2
    Next i
    
    
    
    Exit Sub
    tackle_this:
    ' errors handled here
    MsgBox "You need to select a table so that I can create a tag cloud", vbCritical + vbOKOnly, "Wow, looks like there is an error!"
    End Sub

  7. #7
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    To add any additional stop words I would somehow have to get into the referenced sites I presume
    Yes although there is no reason that you couldn't edit the external JS file and store locally, although it would be a bit of a pain to distribute

  8. #8
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    Yea the distribution part is making this project a little harder than it needs to be...any idea whats causing my other tag cloud generating code to bug out when I try and place the generated cloud on another sheet? With Sheets("Cloud").WebBrowser1 allowed the generated cloud from your code to appear on the cloud worksheet.

    But can't seem to figure out any way for my other "offline" cloud generator (code two posts above) to display anywhere except on the sheet that is active with frequency counts which I really hope to only use as a work sheet (do calculations and the such but not really ever display to the user).

  9. #9
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    I've been working with the code Kyle provided and it's been working nicely. Been able to add stop words and change the colors based on frequencies...still wish I understood how the javascript worked in more detail so I could figure out this next seemingly very simple stupid question:

    How can I add commas to separate the different words/strings. In my case the strings are type descriptions of injuries so separating the descriptions so the user can quickly visualize the injury types they need to focus on is important. Sorry that this may seem like a javascript question but it is still pairing with excel/vba. I believe this change would lie within this bit of code rather than the vba side...

    WordCloud.MAX_UNIT_SIZE = 7;
    WordCloud.RANGE_UNIT_SIZE = WordCloud.MAX_UNIT_SIZE - WordCloud.MIN_UNIT_SIZE;
    
    WordCloud.prototype.draw = function(data, options) {
    
      var wordMap = {};
      var wordList = [];
    
      options = options || {};
      var stopWords = WordCloud.DEFAULT_STOP_WORDS;
      if (options.stopWords) {
        stopWords = {};
        var words = options.stopWords.toLowerCase().split(/ |,/);
        for (var i = 0; i < words.length; i++) {
          stopWords[words[i]] = 1;
        }
      }
    
      for (var rowInd = 0; rowInd < data.getNumberOfRows(); rowInd++) {
        for (var colInd = 0; colInd < data.getNumberOfColumns(); colInd++) {
          if (data.getColumnType(colInd) == 'string') {
            WordCloud.addWords(data.getValue(rowInd, colInd), wordList, wordMap, stopWords);
          }
        }
      }
    
      // Compute frequency range
      var minFreq = 999999;
      var maxFreq = 0;
      for (var word in wordMap) {
        var f = wordMap[word];
        minFreq = Math.min(minFreq, f);
        maxFreq = Math.max(maxFreq, f);
      }
      var range = maxFreq - minFreq;
      range = Math.max(range, 4);
    
      // Idea: Add option to sort by text, freq or no sort
    
      var html = [];
      html.push('<div class="word-cloud">');
      for (var i = 0; i < wordList.length; i++) {
        var word = wordList[i];
        var text = word;
        var freq = wordMap[word.toLowerCase()];
        var size = WordCloud.MIN_UNIT_SIZE +
             Math.round((freq - minFreq) / range * WordCloud.RANGE_UNIT_SIZE);
        html.push('<span class="word-cloud-', size, '">', text, '</span> ');
      }
      html.push('</div>');
    
      this.container.innerHTML = html.join('');
    };

  10. #10
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    Hey in case anyone else could find this useful. Still working on some other details of the project and have a thread open here http://www.mrexcel.com/forum/showthr...=1#post3012941 describing the main issue I'm trying to figure out. Hope this can help someone. Thanks again for your help Kyle.

    /*
    
    A list of words, where the size and color of each word is determined
    by the number of times it appears in the text.
    Uses the Google Visalization API.
    
    Data Format
      Any number of rows and columns.
      All string values are concatenated, other column types are ignored.
    
    Configuration options:
      none
    
    Methods
      none
    
    Events
      none
    
    */
    
    WordCloud = function(container) {
      this.container = container;
    }
    
    //stopWords Array...to replace BLANK/NULL neccessary to have the backslash (\) as an escape character in order for replace to work 
    WordCloud.stopWords= new Array();
    
    WordCloud.stopWords[0] = ",";
    WordCloud.stopWords[1] = "-";
    
    // Add all word in a given text to a list and map.
    // list is a list of unique words.
    // map is a set of all found words.
    
    /*Commented out WordCloud.addWords because all it does is calls WordCloud.addWord
       WordCloud.addWords = function(text, list, map) {
    
            WordCloud.addWord(text, list, map);
    
      };
    */
      
    // Add a single word to a list and map.
    // list is a list of unique words.
    // map is a set of all found words.
    
    WordCloud.addWord = function(text, list, map) {
      var wl = text.toLowerCase();
     
      if (map[wl]) {
        map[wl]++;
      } else {
        map[wl] = 1;
        list.push(text);
      }
    };
    
    WordCloud.MIN_UNIT_SIZE = 1;
    WordCloud.MAX_UNIT_SIZE = 7;
    WordCloud.RANGE_UNIT_SIZE = WordCloud.MAX_UNIT_SIZE - WordCloud.MIN_UNIT_SIZE;
    
    WordCloud.prototype.draw = function(data, options) {
    
    var wordMap = {};
      var wordList = [];
    	
    //for each row and column add one to the row and column counts
        for (var rowInd = 0; rowInd < data.getNumberOfRows(); rowInd++) {
        for (var colInd = 0; colInd < data.getNumberOfColumns(); colInd++) {
    	
    //if the column data is a string
          if (data.getColumnType(colInd) == 'string') {
    	  
    	//Set the variable "CellContents" equal to the value of the columns/rows
    	var CellContents = data.getValue(rowInd, colInd);
    	
    	//Convert all CellContents to lower case capitalization
    	CellContents = CellContents.toLowerCase();
    	
    	//Globally replace all commas with "" (nothing) i.e. remove them as to make seperation more easily discernable in the word cloud.
    	for (i=0; i<=WordCloud.stopWords.length;i++)
    	{
    	
    	MyRegExp = new RegExp(WordCloud.stopWords[i], "g");
    	CellContents = CellContents.replace(MyRegExp,"");
    	
    	}
    	
    	//The addwords of WordCloud are a function of CellContents, wordList, and wordMap
    		//WordCloud.addWords(CellContents, wordList, wordMap);
            WordCloud.addWord(CellContents, wordList, wordMap);
          }
        }
      }
    
    // Compute frequency range...set max = 0 and min = 999999? 
      var minFreq = 999999;
      var maxFreq = 0;
      
    // for each word in wordMap 
      for (var word in wordMap) {
    	
    	//Set the variable f = wordMap function (which is a function of word)
        var f = wordMap[word];
    	
    	//Set minFreq equal to whichever is less between minFreq and f
        minFreq = Math.min(minFreq, f);
    	
    	//Set maxFreq equal to whichever is less between maxFreq and f
        maxFreq = Math.max(maxFreq, f);
      }
      
    //Set the variable "range" equal to the difference between maxFreq and minFreq
      var range = maxFreq - minFreq;
      
      //By setting range - to the max of range and 4, if the range is less than 4 it will be set to 4
      range = Math.max(range, 4);
    
      // Idea: Add option to sort by text, freq or no sort
    
      //create empy html variable
      var html = [];
      
      //Initiate HTML push
      html.push('<div class="word-cloud">');
      
     
      for (var i = 0; i < wordList.length; i++) {
        var word = wordList[i];
        var text = word;
        var freq = wordMap[word.toLowerCase()];
        var size = WordCloud.MIN_UNIT_SIZE +
             Math.round((freq - minFreq) / range * WordCloud.RANGE_UNIT_SIZE);
    
         html.push('<span class="word-cloud-', size, '">', text, '</span> ');
    
    //Place a comma after the printed description as long as it is not the last description
     if (i < wordList.length-1) {
          html.push('<font size="7">,</font>');
    }
    
      }
      
      //End HTML Push
      html.push('</div>');
    
      this.container.innerHTML = html.join('');
      
    };
    Last edited by VTHokie11; 01-24-2012 at 02:55 PM. Reason: Had to take out some commenting w/in code.

  11. #11
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    Hey in case anyone else could find this useful. Still working on some other details of the project and have a thread open here http://www.mrexcel.com/forum/showthr...=1#post3012941 describing the main issue I'm trying to figure out. Hope this can help someone. Thanks again for your help Kyle.

    /*
    
    A list of words, where the size and color of each word is determined
    by the number of times it appears in the text.
    Uses the Google Visalization API.
    
    Data Format
      Any number of rows and columns.
      All string values are concatenated, other column types are ignored.
    
    Configuration options:
      none
    
    Methods
      none
    
    Events
      none
    
    */
    
    WordCloud = function(container) {
      this.container = container;
    }
    
    //stopWords Array...to replace BLANK/NULL neccessary to have the backslash (\) as an escape character in order for replace to work 
    WordCloud.stopWords= new Array();
    
    WordCloud.stopWords[0] = ",";
    WordCloud.stopWords[1] = "-";
    WordCloud.stopWords[2] = "noc";
    WordCloud.stopWords[3] = "blank\/null";
    
    // Add all word in a given text to a list and map.
    // list is a list of unique words.
    // map is a set of all found words.
    
    /*Commented out WordCloud.addWords because all it does is calls WordCloud.addWord
       WordCloud.addWords = function(text, list, map) {
    
            WordCloud.addWord(text, list, map);
    
      };
    */
      
    // Add a single word to a list and map.
    // list is a list of unique words.
    // map is a set of all found words.
    
    WordCloud.addWord = function(text, list, map) {
      var wl = text.toLowerCase();
     
      if (map[wl]) {
        map[wl]++;
      } else {
        map[wl] = 1;
        list.push(text);
      }
    };
    
    WordCloud.MIN_UNIT_SIZE = 1;
    WordCloud.MAX_UNIT_SIZE = 7;
    WordCloud.RANGE_UNIT_SIZE = WordCloud.MAX_UNIT_SIZE - WordCloud.MIN_UNIT_SIZE;
    
    WordCloud.prototype.draw = function(data, options) {
    
    var wordMap = {};
      var wordList = [];
    	
    //for each row and column add one to the row and column counts
        for (var rowInd = 0; rowInd < data.getNumberOfRows(); rowInd++) {
        for (var colInd = 0; colInd < data.getNumberOfColumns(); colInd++) {
    	
    //if the column data is a string
          if (data.getColumnType(colInd) == 'string') {
    	  
    	//Set the variable "CellContents" equal to the value of the columns/rows
    	var CellContents = data.getValue(rowInd, colInd);
    	
    	//Convert all CellContents to lower case capitalization
    	CellContents = CellContents.toLowerCase();
    	
    	//Globally replace all commas with "" (nothing) i.e. remove them as to make seperation more easily discernable in the word cloud.
    	for (i=0; i<=WordCloud.stopWords.length;i++)
    	{
    	
    	MyRegExp = new RegExp(WordCloud.stopWords[i], "g");
    	CellContents = CellContents.replace(MyRegExp,"");
    	
    	}
    	
    	//The addwords of WordCloud are a function of CellContents, wordList, and wordMap
    		//WordCloud.addWords(CellContents, wordList, wordMap);
            WordCloud.addWord(CellContents, wordList, wordMap);
          }
        }
      }
    
    // Compute frequency range...set max = 0 and min = 999999? 
      var minFreq = 999999;
      var maxFreq = 0;
      
    // for each word in wordMap 
      for (var word in wordMap) {
    	
    	//Set the variable f = wordMap function (which is a function of word)
        var f = wordMap[word];
    	
    	//Set minFreq equal to whichever is less between minFreq and f
        minFreq = Math.min(minFreq, f);
    	
    	//Set maxFreq equal to whichever is less between maxFreq and f
        maxFreq = Math.max(maxFreq, f);
      }
      
    //Set the variable "range" equal to the difference between maxFreq and minFreq
      var range = maxFreq - minFreq;
      
      //By setting range - to the max of range and 4, if the range is less than 4 it will be set to 4
      range = Math.max(range, 4);
    
      // Idea: Add option to sort by text, freq or no sort
    
      //create empy html variable
      var html = [];
      
      //Initiate HTML push
      html.push('<div class="word-cloud">');
      
     
      for (var i = 0; i < wordList.length; i++) {
        var word = wordList[i];
        var text = word;
        var freq = wordMap[word.toLowerCase()];
        var size = WordCloud.MIN_UNIT_SIZE +
             Math.round((freq - minFreq) / range * WordCloud.RANGE_UNIT_SIZE);
    
         html.push('<span class="word-cloud-', size, '">', text, '</span> ');
    
    //Place a comma after the printed description as long as it is not the last description
     if (i < wordList.length-1) {
          html.push('<font size="7">,</font>');
    }
    
      }
      
      //End HTML Push
      html.push('</div>');
    
      this.container.innerHTML = html.join('');
      
    };

  12. #12
    Registered User
    Join Date
    10-26-2011
    Location
    Virginia
    MS-Off Ver
    Excel 2010
    Posts
    50

    Re: JQuery Google Visualizations Intro / Tag (Word) Cloud Generator

    Although I was just thinking the only reason I'm trying to figure out the problem cited the other thread is to get the frequency counts of all the words, which I know could also be accessed through the jscript and html push...I know this is a vba forum but anyone have any advice for how to edit the above jscript code to display the actual frequency counts? And perhaps sum and display the top five frequency counts?

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1