Color Bars That Belong To a Specific Category (e.g. Product)

From Q
Jump to: navigation, search

Colors each bar in a chart red, based on recognition of the client's brand name.

To test this example:

  1. Open C:\Program Files\Q\Examples\Cola.Q (this may be located on a different place on your computer depending upon how Q was installed).
  2. Select Preferred cola in the blue dropdown.
  3. Change the table into a bar or column chart (this example works on both).
  4. Click Edit | Plot JavaScript.
  5. Paste the example below.
 
var coke_row = table.rowIndex('Coca Cola');
if (coke_row != -1) {    // There is a Coca Cola bar here!
    // Fetch the array of cell colors (one entry for each cell).
    var colors = table.cellColors;
    // For all cells on this bar/row, set the color.
    for (var column = 0; column < table.numberColumns; column++)// for loop
        colors[coke_row][column] = 'OrangeRed';
    // Store array of cell colors we just modified.
    table.cellColors = colors;
}

Note that:

  • table.rowIndex('Coca Cola '); is finding the row in the table with a name of 'Coca Cola '.
  • 'Coca Cola ' contains a space at the end. This is because the Label in the project does, for some strange reason, contain this space. If you were to instead use 'Coca Cola' it would not be idenfified (unless you changed the label).
  • An If Statement has been used and most of the code only runs if coke_row != -1 is evaluated as true, where != , means "not equals" and the reason that -1 is being used is that rowIndex returns a value of -1 in the event that it cannot find something (and also a 0 if it finds it in the first row, a 1 in the second row, etc.).
  • The For Loop goes through and makes the change to all the rows columns in the underlying table. In this example there are no columns (remember, it started as a SUMMARY of a Pick One question. However, this code ensures that if we use a Grid Question or use this code on a table with something selected in the Brown drop-down menu then all the Coca Cola columns or bars will go red).
  • A list of different colors is at JavaScript Color Table.
  • The object containing the colors, colors, is an Array, where each element in the array relates to a row and, this element is, initself, another Array, where each element refers to the column within the array.
  • Having modified the array we then need to tell Q to use the modified array, which is what occurs with the code table.cellColors = colors;

See also