2016-09-12 5 views
5

나는 당신이 아마 각자 제작 한 barchart를 생각하고 있다는 것을 알고 있는가? 왜 기존 도서관이 없습니까? 500 개 밖에 필요하지 않지만 코드 20000 줄의 파일을 사용하는 것은 싫다.자수성 barchart에 전설 추가

아, 재미 있습니다 :) 주요 목표는 Phonegap을 사용하여 만들 수있는 앱에이 스크립트를 사용하는 것입니다. 크기가 작을수록 좋습니다. enter image description here

나는 부모의 높이에 따라 그들이 동일한 폭으로되어 있는지 확인, 막대를 그릴 수 있었다 그들의 높이가했습니다

그래서 아이디어는 다음과 달성하는 것입니다 컨테이너. 아래 코드에서 볼 수 있듯이 옵션에 글꼴 크기를 추가했습니다. 일부 차트는 300px 높이로 확장됩니다 (예 : 기본 16px 사용). 글꼴 크기가 12 이하인 글꼴은 50px 밖에되지 않습니다. 그래서 ChartContainer를 글꼴 크기 (+ 나머지) 3 x 줄이면 상단 (금액)에 대한 공간이 충분합니다. & 하단 (범례 + 제목)

어떻게 추가 할 것인지 잘 모르겠습니다. 금액을 중심에 두십시오. 필자는 기존 차트 라이브러리를 검색하여 모든 렌더링 방법을 확인했지만 불행히도 모두 캔버스 또는 SVG 컨테이너를 사용했습니다. 어떤 제안?

/* dataset 
 
    ------------------ 
 

 
    add legends 
 
    add result/amount 
 
    add bottom-border: 8px extra to both sides? 
 
    add chart name 
 

 
*/ 
 

 
(function ($) { 
 

 
    var methods = { 
 
     init : function(options) { 
 
      return this.each(function() { 
 

 
       var $this = $(this), 
 
        dataset = options.dataset, 
 
        fontSize = options.fontSize, 
 
        widthOfContainer = $this.width(), 
 
        heightOfContainer = $this.height() - (3 * (fontSize + 4)), // make room for title (bottom), legend (bottom), amounts (top) 
 
        widthOfBar = parseInt(widthOfContainer/options.dataset.length) - 2, 
 
        bar; 
 

 
       $this.bind('draw', function(e) { 
 
        $this.empty(); 
 

 
        var maxValueInDataset = Math.max.apply(Math, dataset.map(function(o){return o.a;})), 
 
         heightPerUnit = parseInt(heightOfContainer/maxValueInDataset); 
 
        for (var i = 0; i < dataset.length; i++) { 
 
         bar = $(document.createElement('div')); 
 
         bar.addClass('bar'); 
 
         bar.css({ 
 
          'height': parseInt(dataset[i].a * heightPerUnit) + 'px', 
 
          'width': parseInt(widthOfBar) + 'px', 
 
          'margin-left': parseInt(i * 2 + i * widthOfBar) + 'px', 
 
          'bottom': 2 * (fontSize + 4) 
 
         }); 
 
         $this.append(bar); 
 
        } 
 
       }); 
 

 
       $this.trigger('draw'); 
 
      }); 
 
     }, 
 
     draw : function(n) { 
 
      $(this).trigger('draw'); 
 
     } 
 
    }; 
 

 
    $.fn.chart = function(methodOrOptions) { 
 
     if (methods[methodOrOptions]) { 
 
      return methods[ methodOrOptions ].apply(this, Array.prototype.slice.call(arguments, 1)); 
 
     } else if (typeof methodOrOptions === 'object' || ! methodOrOptions) { 
 
      // Default to "init" 
 
      return methods.init.apply(this, arguments); 
 
     } else { 
 
      $.error('Method ' + methodOrOptions + ' does not exist on jQuery.tooltip'); 
 
     } 
 
    }; 
 

 
    $(document).ready(function(){ 
 
     $('div.barchart').chart({ 
 
      // Add font-size? 
 
      fontSize: 14, 
 
      name: 'mana cost', 
 
      dataset: [ 
 
       {a: 2, label: '0'}, 
 
       {a: 8, label: '1'}, 
 
       {a: 9, label: '2'}, 
 
       {a: 4, label: '3'}, 
 
       {a: 7, label: '4'}, 
 
       {a: 3, label: '5'}, 
 
       {a: 1, label: '6'}, 
 
       {a: 1, label: '7'}, 
 
       {a: 2, label: '8'}, 
 
       {a: 5, label: '9'} 
 
      ] 
 
     }); 
 
    }); 
 
}(jQuery));
/* Barchart 
 
    ========================================================================== */ 
 

 
.barchart { 
 
    color: black; 
 
} 
 

 
/* Bar 
 
    ========================================================================== */ 
 

 
.bar { 
 
    position: absolute; 
 
    height: 0px; 
 
    width: 0px; 
 
    margin-left: 0px; 
 
    bottom: 0px; 
 
    background: black; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div style="padding: 20px;"> 
 
      <div class="barchart" style="height: 100px; position: relative"></div> 
 
     </div>

답변

2

니스 차트! 그것은 깨끗해 보인다. 나는 네가 무슨 뜻인지 안다. 나는 bxSlider의 레이아웃을 조작하려고 몇 달을 보냈다. 그런 다음 내 자신의 코드를 작성하는 코드가 적다는 사실을 깨달았다. 다음은 귀하의 질의 응답에 대한 시도입니다. 나는 백분율을 사용하여 너비를 반응 적으로 만들었습니다 (걱정하지 마시고 다시 변경하기 쉽습니다), 범례, 값 및 개수에 대한 추가 css 클래스를 추가하고 이름 옵션 (범례라고 함)을 포함하도록 플러그인을 수정했습니다. . 그러면이 비트는 형식이 지정되고 추가됩니다. 희망이 도움이됩니다.

/* dataset 
 
    ------------------ 
 

 
    add legends 
 
    add result/amount 
 
    add bottom-border: 8px extra to both sides? 
 
    add chart name 
 

 
*/ 
 

 
(function ($) { 
 

 
    var methods = { 
 
     init : function(options) { 
 
      return this.each(function() { 
 

 
       var $this = $(this), 
 
        dataset = options.dataset, 
 
        fontSize = options.fontSize, 
 
        legend = options.name, 
 
        widthOfContainer = $this.width(), 
 
        heightOfContainer = $this.height() - (3 * (fontSize + 4)), // make room for title (bottom), legend (bottom), amounts (top) 
 
        widthOfBar = parseInt(widthOfContainer/options.dataset.length) - 2, 
 
        widthOfBarPer = (widthOfBar/widthOfContainer) *100, 
 
        bar; 
 

 
       $this.bind('draw', function(e) { 
 
        $this.empty(); 
 

 
        var maxValueInDataset = Math.max.apply(Math, dataset.map(function(o){return o.a;})), 
 
         heightPerUnit = parseInt(heightOfContainer/maxValueInDataset); 
 
        for (var i = 0; i < dataset.length; i++) { 
 
        \t \t var dataVal = dataset[i].a; 
 
         bar = $(document.createElement('div')); 
 
         bar.addClass('bar'); 
 
         bar.css({ 
 
          'height': parseInt(dataVal * heightPerUnit) + 'px', 
 
          'width': widthOfBarPer + '%', // percentages to make more responsive? 
 
          'margin-left': (i + i * widthOfBarPer) + '%', // no need to parseInt as you have already on widthOfBar. now your chart stretches with the width . 
 
          'bottom': 2 * (fontSize + 4) 
 
         }); 
 
         bar.append('<p class="count">'+ i +'</p>'); \t // defines the bar count, this could be dataset[i].label but if you just use i then you don't need to type it out for each bar? 
 
         bar.append('<p class="value">'+ dataVal +'</p>'); \t // defines the bar value 
 
         $this.append(bar); // adds the bar count 
 
        } 
 
        var chartHeight = $this.height(); 
 
        $('.bar .count').css({ bottom: fontSize - chartHeight * 0.5 }); 
 
        $('.bar .value').css({ bottom: chartHeight * 0.5 - fontSize }); 
 
        if(legend){ 
 
\t \t \t \t \t \t \t \t \t \t \t \t legend = '<p class="legend">'+legend+'</p>'; 
 
\t \t \t \t \t \t \t \t \t \t \t $this.append(legend); 
 
        //  $this.css({ border: '1px solid #f90'}); // temp to see the current chart size 
 
         $this.find('.legend').css({ top: chartHeight - fontSize }); 
 
        } 
 
       }); 
 

 
       $this.trigger('draw'); 
 
      }); 
 
     }, 
 
     draw : function(n) { 
 
      $(this).trigger('draw'); 
 
     } 
 
    }; 
 

 
    $.fn.chart = function(methodOrOptions) { 
 
     if (methods[methodOrOptions]) { 
 
      return methods[ methodOrOptions ].apply(this, Array.prototype.slice.call(arguments, 1)); 
 
     } else if (typeof methodOrOptions === 'object' || ! methodOrOptions) { 
 
      // Default to "init" 
 
      return methods.init.apply(this, arguments); 
 
     } else { 
 
      $.error('Method ' + methodOrOptions + ' does not exist on jQuery.tooltip'); 
 
     } 
 
    }; 
 

 
    $(document).ready(function(){ 
 
     $('div.barchart').chart({ 
 
      // Add font-size? 
 
      fontSize: 14, 
 
      name: 'mana cost', 
 
      dataset: [ 
 
       {a: 2, label: '0'}, 
 
       {a: 8, label: '1'}, 
 
       {a: 9, label: '2'}, 
 
       {a: 4, label: '3'}, 
 
       {a: 7, label: '4'}, 
 
       {a: 3, label: '5'}, 
 
       {a: 1, label: '6'}, 
 
       {a: 1, label: '7'}, 
 
       {a: 2, label: '8'}, 
 
       {a: 5, label: '9'} 
 
      ] 
 
     }); 
 
    }); 
 
}(jQuery));
/* Barchart 
 
    ========================================================================== */ 
 

 
.barchart { 
 
    color: black; 
 
} 
 

 
/* Bar 
 
    ========================================================================== */ 
 

 
.bar { 
 
    position: absolute; 
 
    height: 0px; 
 
    width: 0px; 
 
    margin-left: 0px; 
 
    bottom: 0px; 
 
    background: black; 
 
} 
 

 
.count, .value{ 
 
    z-index: 7; 
 
    position: absolute; 
 
    text-align: center; 
 
    width: 100%; 
 
} 
 

 
.legend{ 
 
    position: relative; 
 
    text-align: center; 
 
    width: 100%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div style="padding: 20px;"> 
 
      <div class="barchart" style="height: 100px; position: relative"></div> 
 
     </div>

2

엄지 손가락 코드 —의 불필요한 금액을 피하기위한 깨끗한 막대 그래프는 거대한 라이브러리를 필요로하지 않는 완벽한 예입니다. 당신이에서 막대 그래프를 만들 수있는 기본 구조로 <table>를 사용하는 경우

, 당신은 —이 적은 코드의 결과로 원하는 서식 옵션에 쉽게 액세스 할 수 있습니다 : 값에 대한

  • 한 행 한 행
  • 바 (B)를 중심으로하는 범례 <caption> 추가 각 값 셀
  • 텍스트 테이블 셀 내에서 중심으로 할 수
  • border-bottom을 스타일링 할 수 레이블 y 기본값이며 caption-side 속성을 사용하여 테이블 아래에 쉽게 놓을 수 있습니다.
  • 값 셀의 스타일을 지정하면 막대의 바로 위에 값을 배치하거나 (아래의 데모에서와 같이) 값을 위쪽에 배치 할 수 있습니다 그림) — 이것은 아래 js 데모 코드의 20 행에서 제어됩니다.

결국, barchart는 테이블 형식 데이터의 단순화에 불과하므로 테이블을 사용하는 것이 좋습니다.

function barchart(containerId, options) { 
 
    var i, 
 
     html, 
 
     valueRow = '', 
 
     labelRow = '', 
 
     data = options.dataset, 
 
     maxBarHeight = 60, /* in px, could be set from options */ 
 
     barWidth = 20,  /* in px, could be set from options */ 
 
     maxValue = Math.max.apply(
 
     Math, 
 
     data.map(function(o) { 
 
      return o.a; 
 
     }) 
 
    ); 
 
    for(i = 0; i < data.length; i++){ 
 
    labelRow += '<td>' + data[i].label + '</td>'; 
 
    valueRow += '<td style="border-bottom:' + 
 
     (data[i].a * maxBarHeight/maxValue) + 
 
     'px solid black;vertical-align:' + 
 
     'bottom' + /* set to 'top' to get value labels lined up */ 
 
     ';width: ' + 
 
     barWidth + 'px">' + 
 
     data[i].a + '</td>'; 
 
    } 
 
    html = '<table class="barchart" ' + 
 
    'style="font-size:' + options.fontSize + 'px">' + 
 
    '<caption>' + options.name + '</caption>' + 
 
    '<tr>' + valueRow + '</tr>' + 
 
    '<tr>' + labelRow + '</tr>' + 
 
    '</table>'; 
 
    document.getElementById(containerId) 
 
    .innerHTML = html; 
 
} 
 

 
/* create a barchart */ 
 

 
barchart('testdiv', { 
 
    fontSize: 14, 
 
    name: 'mana cost', 
 
    dataset: [ 
 
    {a: 2, label: '0'}, 
 
    {a: 8, label: '1'}, 
 
    {a: 9, label: '2'}, 
 
    {a: 4, label: '3'}, 
 
    {a: 7, label: '4'}, 
 
    {a: 3, label: '5'}, 
 
    {a: 1, label: '6'}, 
 
    {a: 1, label: '7'}, 
 
    {a: 2, label: '8'}, 
 
    {a: 5, label: '9'} 
 
    ] 
 
});
.barchart td{ 
 
    text-align: center; 
 
} 
 

 
.barchart{ 
 
    font-family: 'arial narrow', sans-serif; 
 
    caption-side: bottom; 
 
}
<div id="testdiv"></div>

+0

이 ISN '(약 30 바닐라 JS의 라인과 필요한 경우 쉽게 JQuery와 접근 방식에 적응할 수 CSS, 몇 줄의)

워킹 데모 응답의 t도 나쁜! 고마워, 그것을 볼 것이다. – Goowik