Подтвердить что ты не робот

Используя Chartist.js, как вы изменяете цвет штриха для диаграммы пончиков?

Привет, я пытаюсь создать следующую диаграмму пончика, используя Chartist.js:

ЦЕЛЬ ИСТОРИИ

Вот как выглядит диаграмма в настоящее время:

Диаграмма чарта Chartist.js

Я пытаюсь найти, где и как я могу изменить цвета этой диаграммы в соответствии с первой диаграммой пончиков. Красный и розовый, по-видимому, являются значениями по умолчанию. Я не смог найти документацию о том, как достичь этой цели. Я также хотел бы настроить размер штриха и размер самой диаграммы. Любая помощь очень ценится!

Текущий код:

// ** START CHARTIST DONUT CHART ** //
var chart = new Chartist.Pie('.ct-chart', {
  series: [70, 30],
  labels: [1, 2]
}, {
  donut: true,
  showLabel: false
});
chart.on('draw', function(data) {
  if(data.type === 'slice') {
    // Get the total path length in order to use for dash array animation
    var pathLength = data.element._node.getTotalLength();

    // Set a dasharray that matches the path length as prerequisite to animate dashoffset
    data.element.attr({
      'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
    });
    // Create animation definition while also assigning an ID to the animation for later sync usage
    var animationDefinition = {
      'stroke-dashoffset': {
        id: 'anim' + data.index,
        dur: 1000,
        from: -pathLength + 'px',
        to:  '0px',
        easing: Chartist.Svg.Easing.easeOutQuint,
        // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
        fill: 'freeze'
      }
    };
    // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
    if(data.index !== 0) {
      animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
    }
    // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
    data.element.attr({
      'stroke-dashoffset': -pathLength + 'px'
    });
    // We can't use guided mode as the animations need to rely on setting begin manually
    // See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
    data.element.animate(animationDefinition, false);
  }
});
// ** END CHARTIST DONUT CHART ** //

HTML:

<div class="ct-chart ct-perfect-fourth"></div>
4b9b3361

Ответ 1

Итак, я понял это...

Мне пришлось перейти в css и переопределить значения по умолчанию. Я должен был убедиться, что файл css был загружен после cdn для Chartist. Затем просто установите ширину и высоту ct-диаграммы.

.ct-series-a .ct-bar, .ct-series-a .ct-line, .ct-series-a .ct-point, .ct-series-a .ct-slice-donut {
    stroke: #0CC162;
}
.ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
    stroke: #BBBBBB;
}
.ct-chart {
    margin: auto;
    width: 300px;
    height: 300px;
}

Затем мне пришлось добавить к объекту диаграммы ключ donutWidth для установки ширины штриха:

var chart = new Chartist.Pie('.ct-chart', {
  series: [7, 3],
  labels: [1, 2]
}, {
  donut: true,
  donutWidth: 42,
  showLabel: false
});

Ответ 2

Chartist полагается на модификацию CSS для управления цветами, размерами и т.д. диаграмм. Я бы предложил посмотреть здесь документацию, чтобы узнать много интересных советов и трюков: https://gionkunz.github.io/chartist-js/getting-started.html

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

/* Donut charts get built from Pie charts but with a fundamentally difference in the drawing approach. The donut is drawn using arc strokes for maximum freedom in styling */
.ct-series-a .ct-slice-donut {
  /* give the donut slice a custom colour */
  stroke: blue;
  /* customize stroke width of the donut slices in CSS. Note that this property is already set in JavaScript and label positioning also relies on this. In the right situation though it can be very useful to style this property. You need to use !important to override the style attribute */
  stroke-width: 5px !important;
  /* create modern looking rounded donut charts */
  stroke-linecap: round;
}

Ответ 3

Мне удалось изменить цвет штриха, переопределив этот класс. Вы можете изменить ct-series-b, на который вы переходите, чтобы изменить цвет (ct-series-a, ct-series-b и т.д.).

<html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.css" />
    <style>
        .ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
             stroke: goldenrod;
        }
    </style>
  </head>
  <body>
    <div class="ct-chart ct-perfect-fourth"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.js"></script>
    <script>
      window.onload = function() {
        var data = {
          labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
          series: [
            [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8],
            [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4]
          ]
        };

        var options = {
          seriesBarDistance: 10
        };

        var responsiveOptions = [
          ['screen and (max-width: 640px)', {
            seriesBarDistance: 5,
            axisX: {
              labelInterpolationFnc: function (value) {
                return value[0];
              }
            }
          }]
        ];

        new Chartist.Bar('.ct-chart', data, options, responsiveOptions);
      }
    </script>
  </body>
</html>

Ответ 4

Немного позже, но вы можете предоставить имена классов в серии данных, чтобы вы могли независимо менять цвета на каждом графике:

Из документов:

Свойство series также может быть массивом объектов значений, которые содержат свойство value и свойство className для переопределения класса CSS имя группы серий.

Вместо

series: [70, 30]

Сделайте это:

series: [{value: 70, className: 'foo'}, {value: 30, className: 'bar'}]

а затем вы можете стилизовать, однако, с помощью свойства stroke css