Диаграмма JS - цвета сетки и градиентная заливка не отображаются - PullRequest
1 голос
/ 26 февраля 2020

У меня есть следующий график:

var canvas = document.getElementById('chart');

var data = {
    labels: ["Q1","Q2","Q3","Q4","Q5"],
    
    datasets: [
        {
            label: "Your answers",
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "rgba(75,192,192,1)",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 5,
            decimals : false,
            pointHitRadius: 10,
            data: [3,5,6,3,7],
            stack: 4
        },
        
        
         {
            label: "Average answers",
            fill: false,
            lineTension: 0.1,
           
            borderColor: "rgba(79,104,241,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "rgba(79,104,241,1)",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(79,104,241,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 5,
            decimals : false,
            pointHitRadius: 10,
            data: [2,7,5,10,3],
            stack: 5
        },
        
        {
        label: "Your average",  
            pointStyle: 'line',
            fill: false,
            borderColor: "#ffffff",
            borderCapStyle: 'round',
            borderDash: [0.5,5],
            borderDashOffset: 1,
            lineTension: 0.1,
            data: [5,5,5,5,5],
            
        }, 
        {
        label: "Audit average",
            pointStyle: 'line',
            fill: false,
            borderColor: "#ffffff",
            borderCapStyle: 'round',
            borderDash: [5,8],
            borderDashOffset: 0.6,
            lineTension: 0.1,
            data: [7,7,7,7,7],
        },
    ]
};

var option = {

    plugins: {
        filler: {
            propagate: true
        }
    },

    legend : {
        display:false
    },

    showLines: true,
        scales: {
            yAxes: [{
                gridLines: {
                    color: 'rgb(255, 255, 255)', 
                    display: true,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Scores'
                },
             
                stacked: false,
                    ticks: {
                        beginAtZero: 0,
                        suggestedMin: 1,
                        suggestedMax: 10,
                        stepSize: 2,
                        
                        userCallback: function(label, index, labels) {
                        // when the floored value is the same as the value we have a whole number
                        if (Math.floor(label) === label) {
                            return label;
                        }
                    },
                }
            }],
            xAxes: [{
                gridLines: {
                    color: 'rgb(255, 255, 255)', 
                    display: true,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Questions'
                },
            }]
        },
     
    annotation: {
 
        annotations: [
 
          {
            drawTime: "beforeDatasetsDraw",
            type: "box",
            id: "n",
            xScaleID: "x-axis-0",
            yScaleID: "y-axis-0",
            xMin: "Q1",
            xMax: "Q5",
            yMin: 0,
            yMax: 3.7,
            backgroundColor: "rgba(26,26,26,0.6)",
            borderColor: "rgba(26,26,26,0.6)",
            borderWidth: 1,
      
          },
           {
            drawTime: "beforeDatasetsDraw",
            type: "box",
            xScaleID: "x-axis-0",
            yScaleID: "y-axis-0",
            xMin: "Q1",
            xMax: "Q5",
            yMin: 3.7,
            yMax: 7,
            backgroundColor: 'rgba(88,88,88,0.6)',
            borderColor: 'rgba(88,88,88,0.6)',
            borderWidth: 1,
      
          },
          {
            drawTime: "beforeDatasetsDraw",
            type: "box",
            xScaleID: "x-axis-0",
            yScaleID: "y-axis-0",
            xMin: "Q1",
            xMax: "Q5",
            yMin: 7,
            yMax: 10,
            backgroundColor: 'rgba(31,42,97,0.6)',
            borderColor: 'rgba(88,88,88,0.6)',
            borderWidth: 0,
      
          }
        ]
      }
   
};

 
var myLineChart = Chart.Line(canvas,{
    data:data,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            tooltips: {
                mode: 'index'
            },
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
});
.wrap { background-color:#000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.5/chartjs-plugin-annotation.js"></script>



<div class="wrap">

<canvas id="chart" width="400" height="250"></canvas>

</div>

Я пытаюсь добиться двух вещей:

  1. Изменить цвет границы и линии сетки на белый.
  2. Изменить градиентную заливку.

Для 1. У меня есть следующий код, добавленный к x и y:

gridLines: {
   color: 'rgb(255, 255, 255)', 
   display: true,
}

Для 2 у меня есть Цвет фона, определенный в annotation: {

Почему ничего из этого не работает?

Вот визуальный пример того, чего я пытаюсь достичь:

enter image description here

Редактировать:

Я изменил на следующее:

var myLineChart = Chart.Line(document.getElementById('chart'), {
    data: data,
    options: options
});

С учетом вышеизложенного, сетки и цвета фона отображаются так, как я хотел (благодаря uminders ответ). Однако метки / ключа теперь нет.

При следующем:

var myLineChart = Chart.Line(document.getElementById('chart'), {
    data: data,
    options: {
      responsive: true,
      maintainAspectRatio: false
        tooltips: {
            mode: 'index'
        }
    }
});

При вышеизложенном ключ теперь отображается, а линии сетки и цвета фона - нет.

Есть ли здесь какой-то средний уровень? Я хочу и ключ, и цвета.

Ответы [ 2 ]

2 голосов
/ 26 февраля 2020

Чтобы отобразить линии сетки, как ожидается, определите положительный z-индекс слоя сетки следующим образом (см. Конфигурация линии сетки ).

gridLines: {
    color: 'rgb(255, 255, 255)',
    z: 2
},

Чтобы отобразить заливку градиентом, используйте ранее определенный options объект (переименованный из option) при создании диаграммы.

var myLineChart = Chart.Line(document.getElementById('chart'), {
  data: data,
  options: options
});

var data = {
  labels: ["Q1", "Q2", "Q3", "Q4", "Q5"],
  datasets: [{
      label: "Your answers",
      fill: false,
      lineTension: 0.1,
      backgroundColor: "rgba(75,192,192,0.4)",
      borderColor: "rgba(75,192,192,1)",
      borderCapStyle: 'butt',
      borderDash: [],
      borderDashOffset: 0.0,
      borderJoinStyle: 'miter',
      pointBorderColor: "rgba(75,192,192,1)",
      pointBackgroundColor: "rgba(75,192,192,1)",
      pointBorderWidth: 1,
      pointHoverRadius: 5,
      pointHoverBackgroundColor: "rgba(75,192,192,1)",
      pointHoverBorderColor: "rgba(220,220,220,1)",
      pointHoverBorderWidth: 2,
      pointRadius: 5,
      decimals: false,
      pointHitRadius: 10,
      data: [3, 5, 6, 3, 7],
      stack: 4
    },
    {
      label: "Average answers",
      fill: false,
      lineTension: 0.1,
      borderColor: "rgba(79,104,241,1)",
      borderCapStyle: 'butt',
      borderDash: [],
      borderDashOffset: 0.0,
      borderJoinStyle: 'miter',
      pointBorderColor: "rgba(75,192,192,1)",
      pointBackgroundColor: "rgba(79,104,241,1)",
      pointBorderWidth: 1,
      pointHoverRadius: 5,
      pointHoverBackgroundColor: "rgba(79,104,241,1)",
      pointHoverBorderColor: "rgba(220,220,220,1)",
      pointHoverBorderWidth: 2,
      pointRadius: 5,
      decimals: false,
      pointHitRadius: 10,
      data: [2, 7, 5, 10, 3],
      stack: 5
    },
    {
      label: "Your average",
      pointStyle: 'line',
      fill: false,
      borderColor: "#ffffff",
      borderCapStyle: 'round',
      borderDash: [0.5, 5],
      borderDashOffset: 1,
      lineTension: 0.1,
      data: [5, 5, 5, 5, 5],

    },
    {
      label: "Audit average",
      pointStyle: 'line',
      fill: false,
      borderColor: "#ffffff",
      borderCapStyle: 'round',
      borderDash: [5, 8],
      borderDashOffset: 0.6,
      lineTension: 0.1,
      data: [7, 7, 7, 7, 7],
    },
  ]
};

var options = {
  plugins: {
    filler: {
      propagate: true
    }
  },
  responsive: true,
  maintainAspectRatio: false,
  tooltips: {
    mode: 'index'
  },
  showLines: true,
  scales: {
    yAxes: [{
      gridLines: {
        color: 'rgb(255, 255, 255)',
        z: 2
      },
      scaleLabel: {
        display: true,
        labelString: 'Scores'
      },
      stacked: false,
      ticks: {
        beginAtZero: 0,
        suggestedMin: 1,
        suggestedMax: 10,
        stepSize: 2,
        userCallback: function(label, index, labels) {
          // when the floored value is the same as the value we have a whole number
          if (Math.floor(label) === label) {
            return label;
          }
        },
      }
    }],
    xAxes: [{
      gridLines: {
        color: 'rgb(255, 255, 255)',
        z: 2
      },
      scaleLabel: {
        display: true,
        labelString: 'Questions'
      },
    }]
  },
  annotation: {
    annotations: [
      {
        drawTime: "beforeDatasetsDraw",
        type: "box",
        id: "n",
        xScaleID: "x-axis-0",
        yScaleID: "y-axis-0",
        xMin: "Q1",
        xMax: "Q5",
        yMin: 0,
        yMax: 3.7,
        backgroundColor: "rgba(26,26,26,0.6)",
        borderColor: "rgba(26,26,26,0.6)",
        borderWidth: 1,

      },
      {
        drawTime: "beforeDatasetsDraw",
        type: "box",
        xScaleID: "x-axis-0",
        yScaleID: "y-axis-0",
        xMin: "Q1",
        xMax: "Q5",
        yMin: 3.7,
        yMax: 7,
        backgroundColor: 'rgba(88,88,88,0.6)',
        borderColor: 'rgba(88,88,88,0.6)',
        borderWidth: 1,

      },
      {
        drawTime: "beforeDatasetsDraw",
        type: "box",
        xScaleID: "x-axis-0",
        yScaleID: "y-axis-0",
        xMin: "Q1",
        xMax: "Q5",
        yMin: 7,
        yMax: 10,
        backgroundColor: 'rgba(31,42,97,0.6)',
        borderColor: 'rgba(88,88,88,0.6)',
        borderWidth: 0
      }
    ]
  }
};

var myLineChart = Chart.Line(document.getElementById('chart'), {
  data: data,
  options: options
});
canvas { background-color:#000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>

<canvas id="chart" width="400" height="250"></canvas>
0 голосов
/ 26 февраля 2020

Почему вы не используете var option переменную в объявлениях? например:

var myLineChart = Chart.Line(canvas,{
    data:data,
    options: option 
});
...