jqplot - 根据标签名称为条形图设置自定义颜色

时间:2014-05-25 16:39:58

标签: backbone.js jqplot

我有一个骨干应用程序,可动态呈现具有不同数据集的多个条形图,我无法知道将显示哪个标签名称。例如,如果给出一组标签:“草莓”,“香草”,“巧克力”,我想在每次该类别显示在图表中时将“草莓”的颜色设置为粉红色。

有没有办法根据标签值在条形图上设置特定颜色?

这是我目前的代码:

collectCategories: function(aggregates) {
  var categories = {};
  _.each(aggregates, function(aggregate) {
   for (var category in aggregate) {
    categories[category] = true;
  }
});
  categories = _.keys(categories);
  categories.sort();
  return categories;
},

render: function() {
  var container = this.$el;
  container.empty();

  var aggregates = this.collection.map(function(purchase) {      
   return purchase.aggregates();
  });

 var categories = this.collectCategories(aggregates);

 var datasets = _.map(categories, function(category) {
 var row = _.map(aggregates, function(aggregate) {
  var qtyInCategory = aggregate[category];
  return qtyInCategory ? qtyInCategory : 0;        
});
  return row;          
});

var labels = this.collection.map(function(purchase) {
  return purchase.get('purchase_date').substr(0, 10);
});

if (datasets.length > 0) {
  this.renderPlot(datasets, labels, categories);
}
return this;
},

renderPlot: function(datasets, labels, categories) {
var seriesLabels = _.map(categories, function(category) {
  return { label: category};
});

var customSeriesColors = 

var plot = $.jqplot('bar-charts-container', datasets, {
  stackSeries: true,
  captureRightClick: true,
  seriesDefaults:{
    renderer:$.jqplot.BarRenderer,
    rendererOptions: {
      barMargin: 30,
      varyBarColor: true  
    },
    pointLabels: {        
      show: false
    }
  },

series: seriesLabels,

seriesColors: 

axes: {
  xaxis: {
      renderer: $.jqplot.CategoryAxisRenderer,
      ticks: labels
  },
  yaxis: {
    padMin: 0
  }
},

legend: {
  show: true,
  location: 'e',
  placement: 'outside'
}      
});

1 个答案:

答案 0 :(得分:0)

由于您在绘图时可以访问标签,为什么不在那里定义颜色呢?

seriesColors: colorsForLabels(seriesLabels)

对象的其他地方:

colorsForLabels: function(labels) {
  return _.map(labels, function(labelObj) {
    switch (labelObj.label) {
      case 'strawberry':
        return 'pink';
      case: 'vanilla':
        return 'white';
      default:
        # return a random colour from a list
    }
  });
}

default是一个悬而未决的问题;如果您 的标签与预定义列表不匹配,则必须从备选列表中进行选择。