[Chartjs]-Chartkick column_chart different colors not working

1👍

Finally found a working solution for now though I don’t think that it is the ideal one.

What I did was I removed the colors in the options that I have set in config/initializers/Chartkick.rb and passed it instead as I render the json in my controller. So my controller method looks like:

# detected_vehicles_controller (API)
  before_action :load_data

  def by_total_count_per_vehicle_type
    chart_data = @detected_vehicles.group(:vehicle_type).count
    render json: [{ data: parse_vehicle_type_data(chart_data),
                    library: background_color }].chart_json
  end

  private

  def load_data
    query_params = { q: { 'detection_time_eq' => @date, 'camera_camera_area_eq' => @location } }
    @detected_vehicles = DetectedVehicle.search_by_params(query_params)
  end

  def parse_vehicle_type_data(data)
    vehicle_type_datasets = []
    data.each do |key, value|
      dataset = {}
      dataset['name'] = key
      dataset['data'] = { key => value }
      vehicle_type_datasets << dataset
    end
  end

  def background_color
    {
      fill: false,
      backgroundColor: [
        'rgba(75, 192, 192, 0.2)',
        'rgba(255, 99, 132, 0.2)',
        'rgba(255, 159, 64, 0.2)',
        'rgba(255, 205, 86, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(201, 203, 207, 0.2)'
      ],
      borderColor: [
        'rgba(75, 192, 192)',
        'rgba(255, 99, 132)',
        'rgba(255, 159, 64)',
        'rgba(255, 205, 86)',
        'rgba(54, 162, 235)',
        'rgba(153, 102, 255)',
        'rgba(201, 203, 207)'
      ],
      borderWidth: 2
    }
  end

So my chart now looks like:
enter image description here

Leave a comment