티스토리 뷰






HTML + Javascript 조합으로 구성된 간단한 차트 플러그인

세로막대 차트만 지원한다.


추후 사용자 플러그인 (Custom Plugin) 개발시에 참고하면 괜찮을것 같아서 블로그에 남깁니다.

IE6 이상부터 사용가능 (타 브라우저는 그냥 사용가능)



 jqBarGraph.1.1.js


http://www.workshop.rs/jqbargraph/


기본 사용방법

   1:  arrayOfData = new Array(
   2:         [10.3,'Jan','#f3f3f3'],
   3:         [15.2,'Feb','#f4f4f4'],
   4:         [13.1,'Mar','#cccccc'],
   5:         [16.3,'Apr','#333333'],
   6:         [14.5,'May','#666666']
   7:  ); 

   1:  $('#divForGraph').jqBarGraph({ data: arrayOfData }); 

SOURCE

  1:  /**
   2:   * jqBarGraph - jQuery plugin
   3:   * @version: 1.1 (2011/04/03)
   4:   * @requires jQuery v1.2.2 or later 
   5:   * @author Ivan Lazarevic
   6:   * Examples and documentation at: http://www.workshop.rs/jqbargraph/
   7:   * 
   8:   * Dual licensed under the MIT and GPL licenses:
   9:   *   http://www.opensource.org/licenses/mit-license.php
  10:   *   http://www.gnu.org/licenses/gpl.html
  11:   * 
  12:   * @param data: arrayOfData // array of data for your graph
  13:   * @param title: false // title of your graph, accept HTML
  14:   * @param barSpace: 10 // this is default space between bars in pixels
  15:   * @param width: 400 // default width of your graph ghhjgjhg
  16:   * @param height: 200 //default height of your graph
  17:   * @param color: '#000000' // if you don't send colors for your data this will be default bars color
  18:   * @param colors: false // array of colors that will be used for your bars and legends
  19:   * @param lbl: '' // if there is no label in your array
  20:   * @param sort: false // sort your data before displaying graph, you can sort as 'asc' or 'desc'
  21:   * @param position: 'bottom' // position of your bars, can be 'bottom' or 'top'. 'top' doesn't work for multi type
  22:   * @param prefix: '' // text that will be shown before every label
  23:   * @param postfix: '' // text that will be shown after every label
  24:   * @param animate: true // if you don't need animated appereance change to false
  25:   * @param speed: 2 // speed of animation in seconds
  26:   * @param legendWidth: 100 // width of your legend box
  27:   * @param legend: false // if you want legend change to true
  28:   * @param legends: false // array for legend. for simple graph type legend will be extracted from labels if you don't set this
  29:   * @param type: false // for multi array data default graph type is stacked, you can change to 'multi' for multi bar type
  30:   * @param showValues: true // you can use this for multi and stacked type and it will show values of every bar part
  31:   * @param showValuesColor: '#fff' // color of font for values 
  32:  
  33:   * @example  $('#divForGraph').jqBarGraph({ data: arrayOfData });  
  34:    
  35:  **/
  36:   
  37:  (function($) {
  38:      var opts = new Array;
  39:      var level = new Array;
  40:      
  41:      $.fn.jqBarGraph = $.fn.jqbargraph = function(options){
  42:      
  43:      init = function(el){
  44:   
  45:          opts[el.id] = $.extend({}, $.fn.jqBarGraph.defaults, options);
  46:          $(el).css({ 'width': opts[el.id].width, 'height': opts[el.id].height, 'position':'relative', 'text-align':'center' });
  47:          doGraph(el);
  48:   
  49:      };
  50:      
  51:      // sum of array elements
  52:      sum = function(ar){
  53:          total = 0;
  54:          for(val in ar){
  55:              total += ar[val];
  56:          }
  57:          return total.toFixed(2);
  58:      };
  59:      
  60:      // count max value of array
  61:      max = function(ar){
  62:          maxvalue = 0;
  63:          for(var val in ar){
  64:              value = ar[val][0];
  65:              if(value instanceof Array) value = sum(value);    
  66:              if (parseFloat(value) > parseFloat(maxvalue)) maxvalue=value;
  67:          }    
  68:          return maxvalue;    
  69:      };
  70:   
  71:      // max value of multi array
  72:      maxMulti = function(ar){
  73:          maxvalue = 0;
  74:          maxvalue2 = 0;
  75:          
  76:          for(var val in ar){
  77:              ar2 = ar[val][0];
  78:              
  79:              for(var val2 in ar2){
  80:                  if(ar2[val2]>maxvalue2) maxvalue2 = ar2[val2];
  81:              }
  82:   
  83:              if (maxvalue2>maxvalue) maxvalue=maxvalue2;
  84:          }    
  85:          return maxvalue;        
  86:      };
  87:      
  88:          
  89:      doGraph = function(el){
  90:          
  91:          arr = opts[el.id];
  92:          data = arr.data;
  93:          
  94:          //check if array is bad or empty
  95:          if(data == undefined) {
  96:              $(el).html('There is not enought data for graph');
  97:              return;
  98:          }
  99:   
 100:          //sorting ascending or descending
 101:          if(arr.sort == 'asc') data.sort(sortNumberAsc);
 102:          if(arr.sort == 'desc') data.sort(sortNumberDesc);
 103:          
 104:          legend = '';
 105:          prefix = arr.prefix;
 106:          postfix = arr.postfix;
 107:          space = arr.barSpace; //space between bars
 108:          legendWidth = arr.legend ? arr.legendWidth : 0; //width of legend box
 109:          fieldWidth = ($(el).width()-legendWidth)/data.length; //width of bar
 110:          totalHeight =  $(el).height(); //total height of graph box
 111:          var leg = new Array(); //legends array
 112:          
 113:          //max value in data, I use this to calculate height of bar
 114:          max = max(data);
 115:          colPosition = 0; // for printing colors on simple bar graph
 116:   
 117:           for(var val in data){
 118:               
 119:               valueData = data[val][0];
 120:               if (valueData instanceof Array) 
 121:                   value = sum(valueData);
 122:               else
 123:                   value = valueData;
 124:               
 125:               lbl = data[val][1];
 126:               color = data[val][2];
 127:              unique = val+el.id; //unique identifier
 128:              
 129:               if (color == undefined && arr.colors == false) 
 130:                   color = arr.color;
 131:                   
 132:               if (arr.colors && !color){
 133:                   colorsCounter = arr.colors.length;
 134:                   if (colorsCounter == colPosition) colPosition = 0;
 135:                   color = arr.colors[colPosition];
 136:                   colPosition++;
 137:               }
 138:               
 139:               if(arr.type == 'multi') color = 'none';
 140:                   
 141:               if (lbl == undefined) lbl = arr.lbl;
 142:           
 143:               out  = "<div class='graphField"+el.id+"' id='graphField"+unique+"' style='position: absolute'>";
 144:               out += "<div class='graphValue"+el.id+"' id='graphValue"+unique+"'>"+prefix+value+postfix+"</div>";
 145:               
 146:               out += "<div class='graphBar"+el.id+"' id='graphFieldBar"+unique+"' style='background-color:"+color+";position: relative; overflow: hidden;'></div>";
 147:   
 148:              // if there is no legend or exist legends display lbl at the bottom
 149:               if(!arr.legend || arr.legends)
 150:                   out += "<div class='graphLabel"+el.id+"' id='graphLabel"+unique+"'>"+lbl+"</div>";
 151:               out += "</div>";
 152:               
 153:              $(el).append(out);
 154:               
 155:               //size of bar
 156:               totalHeightBar = totalHeight - $('.graphLabel'+el.id).height() - $('.graphValue'+el.id).height(); 
 157:               fieldHeight = (totalHeightBar*value)/max;    
 158:               $('#graphField'+unique).css({ 
 159:                   'left': (fieldWidth)*val, 
 160:                   'width': fieldWidth-space, 
 161:                   'margin-left': space});
 162:       
 163:               // multi array
 164:               if(valueData instanceof Array){
 165:                   
 166:                  if(arr.type=="multi"){
 167:                      maxe = maxMulti(data);
 168:                      totalHeightBar = fieldHeight = totalHeight - $('.graphLabel'+el.id).height();
 169:                      $('.graphValue'+el.id).remove();
 170:                  } else {
 171:                      maxe = max;
 172:                  }
 173:                  
 174:                   for (i in valueData){
 175:                       heig = totalHeightBar*valueData[i]/maxe;
 176:                       wid = parseInt((fieldWidth-space)/valueData.length);
 177:                       sv = ''; // show values
 178:                       fs = 0; // font size
 179:                       if (arr.showValues){
 180:                           sv = arr.prefix+valueData[i]+arr.postfix;
 181:                           fs = 12; // font-size is 0 if showValues = false
 182:                       }
 183:                       o = "<div class='subBars"+el.id+"' style='height:"+heig+"px; background-color: "+arr.colors[i]+"; left:"+wid*i+"px; color:"+arr.showValuesColor+"; font-size:"+fs+"px' >"+sv+"</div>";
 184:                       $('#graphFieldBar'+unique).prepend(o);
 185:                   }
 186:               }
 187:               
 188:               if(arr.type=='multi')
 189:                   $('.subBars'+el.id).css({ 'width': wid, 'position': 'absolute', 'bottom': 0 });
 190:   
 191:               //position of bars
 192:               if(arr.position == 'bottom') $('.graphField'+el.id).css('bottom',0);
 193:   
 194:              //creating legend array from lbl if there is no legends param
 195:               if(!arr.legends)
 196:                   leg.push([ color, lbl, el.id, unique ]); 
 197:               
 198:               // animated apearing
 199:               if(arr.animate){
 200:                   $('#graphFieldBar'+unique).css({ 'height' : 0 });
 201:                   $('#graphFieldBar'+unique).animate({'height': fieldHeight},arr.speed*1000);
 202:               } else {
 203:                   $('#graphFieldBar'+unique).css({'height': fieldHeight});
 204:               }
 205:               
 206:           }
 207:               
 208:           //creating legend array from legends param
 209:           for(var l in arr.legends){
 210:               leg.push([ arr.colors[l], arr.legends[l], el.id, l ]);
 211:           }
 212:           
 213:           createLegend(leg); // create legend from array
 214:           
 215:           //position of legend
 216:           if(arr.legend){
 217:              $(el).append("<div id='legendHolder"+unique+"'></div>");
 218:               $('#legendHolder'+unique).css({ 'width': legendWidth, 'float': 'right', 'text-align' : 'left'});
 219:               $('#legendHolder'+unique).append(legend);
 220:               $('.legendBar'+el.id).css({ 'float':'left', 'margin': 3, 'height': 12, 'width': 20, 'font-size': 0});
 221:           }
 222:           
 223:           //position of title
 224:           if(arr.title){
 225:               $(el).wrap("<div id='graphHolder"+unique+"'></div>");
 226:               $('#graphHolder'+unique).prepend(arr.title).css({ 'width' : arr.width+'px', 'text-align' : 'center' });
 227:           }
 228:           
 229:      };
 230:   
 231:   
 232:      //creating legend from array
 233:      createLegend = function(legendArr){
 234:          legend = '';
 235:          for(var val in legendArr){
 236:                   legend += "<div id='legend"+legendArr[val][3]+"' style='overflow: hidden; zoom: 1;'>";
 237:                   legend += "<div class='legendBar"+legendArr[val][2]+"' id='legendColor"+legendArr[val][3]+"' style='background-color:"+legendArr[val][0]+"'></div>";
 238:                   legend += "<div class='legendLabel"+legendArr[val][2]+"' id='graphLabel"+unique+"'>"+legendArr[val][1]+"</div>";
 239:                   legend += "</div>";            
 240:          }
 241:      };
 242:   
 243:   
 244:      this.each (
 245:          function()
 246:          { init(this); }
 247:      )
 248:      
 249:  };
 250:   
 251:      // default values
 252:      $.fn.jqBarGraph.defaults = {    
 253:          barSpace: 10,
 254:          width: 400,
 255:          height: 300,
 256:          color: '#000000',
 257:          colors: false,
 258:          lbl: '',
 259:          sort: false, // 'asc' or 'desc'
 260:          position: 'bottom', // or 'top' doesn't work for multi type
 261:          prefix: '',
 262:          postfix: '',
 263:          animate: true,
 264:          speed: 1.5,
 265:          legendWidth: 100,
 266:          legend: false,
 267:          legends: false,
 268:          type: false, // or 'multi'
 269:          showValues: true,
 270:          showValuesColor: '#fff',
 271:          title: false
 272:      };
 273:      
 274:      
 275:      //sorting functions
 276:      function sortNumberAsc(a,b){
 277:          if (a[0]<b[0]) return -1;
 278:          if (a[0]>b[0]) return 1;
 279:          return 0;
 280:      }
 281:      
 282:      function sortNumberDesc(a,b){
 283:          if (a[0]>b[0]) return -1;
 284:          if (a[0]<b[0]) return 1;
 285:          return 0;
 286:      }    
 287:   
 288:  })(jQuery);


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함