2012-01-29 30 views
11

Estoy usando jqPlot para crear un gráfico de barras, pero me encontré con algunos problemas.Tiene problemas con el gráfico de barras jqPlot

Problema 1: Se cortan la primera y la última barra del gráfico. Solo la mitad muestra

Problema 2: No quiero que mis puntos de datos abarquen todo el eje x. ¿Hay que dejar que los datos abarquen todo el eje x?

enter image description here ex: Esto es lo que hace en este momento.

Estos son los datos que estoy pasando en ella

var chartData = [["19-Jan-2012",2.61],["20-Jan-2012",5.00],["21-Jan-2012",6.00]] 

Este es el jQuery que estoy utilizando.

// Plot chart 
     function PlotChart(chartData, numberOfTicks) { 
      $.jqplot.config.enablePlugins = true; 
       var plot2 = $.jqplot('chart1', [chartData], { 
        title: 'Mouse Cursor Tracking', 
        seriesDefaults:{ 
         renderer: $.jqplot.BarRenderer, 
         rendererOptions: { 
          barPadding: 1, 
          barMargin: 15, 
          barDirection: 'vertical', 
          barWidth: 50 
         }, 
         pointLabels: { show: true } 
        }, 
        axes: { 
         xaxis: { 
          pad: 0,  // a factor multiplied by the data range on the axis to give the 
          numberTicks: numberOfTicks, 
          renderer: $.jqplot.DateAxisRenderer, // renderer to use to draw the axis, 
          tickOptions: { 
           formatString: '%b %#d' // format string to use with the axis tick formatter 
          } 
         }, 
         yaxis: { 
          tickOptions: { 
           formatString: '$%.2f' 
          } 
         } 
        }, 
        highlighter: { 
         sizeAdjust: 7.5 
        }, 
        cursor: { 
         show: true 
        } 
       }); 
      } 
+0

cambiar su almohadilla eje x, cambiar o no Hardcore el número de garrapatas. – PriorityMark

+0

He intentado cambiar el pad, pero no hace nada. El número de tics se establece en la cantidad de elementos que se mostrarán ... Intentaré subirlo – chobo

+0

Aumentar el número de elementos no tuvo efecto – chobo

Respuesta

20

De cómo quiere que su trama se vea, se ahorrará un montón de problemas si se cambia a usar un CategoryAxisRenderer en lugar de la DateAxisRenderer. El CategoryAxisRenderer es mucho mejor para mostrar agrupaciones discretas de datos que como una verdadera serie temporal.

var axisDates = ["Jan 19", "Jan 20", "Jan 21"] 
var chartData = [2.61,5.00,6.00] 

     $.jqplot.config.enablePlugins = true; 
      var plot2 = $.jqplot('chart2', [chartData], { 
       title: 'Some Plot', 
       seriesDefaults:{ 
        renderer: $.jqplot.BarRenderer, 
        rendererOptions: { 
         barPadding: 1, 
         barMargin: 15, 
         barDirection: 'vertical', 
         barWidth: 50 
        }, 
        pointLabels: { show: true } 
       }, 
       axes: { 
        xaxis: {        
          renderer: $.jqplot.CategoryAxisRenderer, 
          ticks: axisDates 
        }, 
        yaxis: { 
         tickOptions: { 
          formatString: '$%.2f' 
         } 
        } 
       }, 
       highlighter: { 
        sizeAdjust: 7.5 
       }, 
       cursor: { 
        show: true 
       } 
      }); 

enter image description here

10

DateAxisRenderer está diseñado para gráficos de líneas, no gráficos de barras. Cuando lo combinas con gráficos de barras, simplemente no funciona bien. La idea/objetivo de DateAxisRenderer es hacer un gráfico de tiempo lineal/preciso a través de una fecha/hora. De esta forma, si pierde una entrada de fecha, aún se dibujará para escalar con el tiempo. Verifique sus ejemplos en DateAxisRenderer aquí: http://www.jqplot.com/tests/date-axes.php

Lo que quiere usar es CategoryAxisRenderer. A continuación, puede simplemente anular/crear su propio renderizador de etiquetas y estar listo para continuar. Normalmente, no le conviene agregar elementos vacíos adicionales a un elemento, especialmente si están vacíos; sin embargo, si lo hace, simplemente agréguelos a su matriz de datos.

Aquí hay una jsFiddle haciendo lo que quiere: http://jsfiddle.net/fordlover49/JWhmQ/

Tenga en cuenta que es posible que desee ver en la sección de gestionar los recursos para verificar los archivos que necesita para hacer referencia (además del archivo de jQuery).

Aquí está el Javascript en caso de jsFiddle hace de las suyas:

$.jqplot.config.enablePlugins = true; 
var chartData = [["19-Jan-2012", 2.61], ["20-Jan-2012", 5.00], ["21-Jan-2012", 6.00]]; 

// add a custom tick formatter, so that you don't have to include the entire date renderer library. 
$.jqplot.DateTickFormatter = function(format, val) { 
    // for some reason, format isn't being passed through properly, so just going to hard code for purpose of this jsfiddle 
    val = (new Date(val)).getTime(); 
    format = '%b&nbsp%#d' 
    return $.jsDate.strftime(val, format); 
}; 

function PlotChart(chartData, extraDays) { 
    // if you want extra days, just append them to your chartData array. 
    if (typeof extraDays === "number") { 
     for (var i = 0; i < extraDays; i++) { 
      var actualDate = new Date(chartData[chartData.length - 1]); // convert last entry to actual date 
      var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate() + 1); // create new increased date 
      chartData.push([newDate, 0]); 
     } 
    } 

    var plot2 = $.jqplot('chart1', [chartData], { 
     title: 'Mouse Cursor Tracking', 
     seriesDefaults: { 
      renderer: $.jqplot.BarRenderer, 
      rendererOptions: { 
       barPadding: 1, 
       barWidth: 50 
      }, 
      pointLabels: { 
       show: true 
      } 
     }, 
     axes: { 
      xaxis: { 
       pad: 1, 
       // a factor multiplied by the data range on the axis to give the    
       renderer: $.jqplot.CategoryAxisRenderer, 
       // renderer to use to draw the axis,  
       tickOptions: { 
        formatString: '%b %#d', 
        formatter: $.jqplot.DateTickFormatter 
       } 
      }, 
      yaxis: { 
       tickOptions: { 
        formatString: '$%.2f' 
       } 
      } 
     }, 
     highlighter: { 
      sizeAdjust: 7.5 
     }, 
     cursor: { 
      show: true 
     } 
    }); 
} 

PlotChart(chartData, 3); 
1

Aquí es un simple truco que he utilizado para mostrar un margen.

Creo una fecha de inicio y una fecha de finalización que son, respectivamente, un día antes y un día después de los contenidos que quiero mostrar.

Por ejemplo si quiero mostrar el mes de 2012 Enero

var startingDate = new Date(2012, 0, 0); //=> 31th Dec 2011 
var endingDate = new Date(2012, 1, 1); //=> 1st Feb 2012 

Luego declaro mis propios DateTickFormatter donde no voy Impresión estas dos fechas.

$.jqplot.DateTickFormatter = function(format, val) { 
     if (!format) { 
      format = '%Y/%m/%d'; 
     } 

     if(val==startingDate.getTime() || val==endingDate.getTime()){ 
      return ""; 
     }else{ 
      return $.jsDate.strftime(val, format); 
     } 
    }; 

Luego, en el xaxis puse las siguientes opciones:

xaxis : { 
     renderer:$.jqplot.DateAxisRenderer, 
     min:startingDate, 
     max:endingDate, 
     tickInterval:'1 day' 
} 
Cuestiones relacionadas