Chartist 图例开发入门-文档

2022-03-31  本文已影响0人  大牧莫邪

1、下载引入

(1) bower管理器

bower包管理器,执行命令安装

$ bower install chartist --save

备注:bower方式安装,可以直接下载sass格式的源代码格式的js/css文件,开发人员可以在项目中直接使用它们

(2) css直接引入

一种最快捷的方式就是直接引入下载的chartist编辑的js/css文件,它允许开发人员使用默认的命名方式或者可配置的方式来应用chartist到项目中,也可以通过修改chartist sass源代码文件定制需要的功能

一个简单的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>My first Chartist Tests</title>
    <link rel="stylesheet"
          href="bower_components/chartist/dist/chartist.min.css">
  </head>
  <body>
    <!-- Site content goes here !-->
    <script src="bower_components/chartist/dist/chartist.min.js"></script>
  </body>
</html>

开发人员也可以通过CDN方式优化加载性能,另一个简单的示例:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
    <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
  </head>
</html>

(3) sass

如果项目中要求的定制化要求较高,也可以直接引入sass源代码文件进行定制化开发,如定制编写自己的选择器、定制混合模块或者编写配置文件实现更加符合自己开发习惯的应用格式

当然如果需要通过配置的方式来完成定制,需要将配置文件拷贝到自己的项目文件夹中

$ cp bower_components/chartist/dist/scss/settings/_chartist-settings.scss styles

开发人员可以修改并导入配置文件,然后将拷贝的chartist.scss文件导入项目中进行使用

@import "_my-chartist-settings.scss";
@import "chartist/dist/scss/chartist.scss";

备注:关于默认配置

配置文件中包含了chartist的默认类名称以及相关选项,开发人员可以通过配置文件中mixins的方式修改这些默认配置定制自己的样式名称,常见的默认配置如下:

// Scales for responsive SVG containers
$ct-scales: ((1), (15/16), (8/9), (5/6), (4/5), (3/4), (2/3), (5/8), (1/1.618), (3/5), (9/16), (8/15), (1/2), (2/5), (3/8), (1/3), (1/4)) !default;
$ct-scales-names: (ct-square, ct-minor-second, ct-major-second, ct-minor-third, ct-major-third, ct-perfect-fourth, ct-perfect-fifth, ct-minor-sixth, ct-golden-section, ct-major-sixth, ct-minor-seventh, ct-major-seventh, ct-octave, ct-major-tenth, ct-major-eleventh, ct-major-twelfth, ct-double-octave) !default;

// Class names to be used when generating CSS
$ct-class-chart: ct-chart !default;
$ct-class-chart-line: ct-chart-line !default;
$ct-class-chart-bar: ct-chart-bar !default;
$ct-class-horizontal-bars: ct-horizontal-bars !default;
$ct-class-chart-pie: ct-chart-pie !default;
$ct-class-chart-donut: ct-chart-donut !default;
$ct-class-label: ct-label !default;
$ct-class-series: ct-series !default;
$ct-class-line: ct-line !default;
$ct-class-point: ct-point !default;
$ct-class-area: ct-area !default;
$ct-class-bar: ct-bar !default;
$ct-class-slice-pie: ct-slice-pie !default;
$ct-class-slice-donut: ct-slice-donut !default;
$ct-class-slice-donut-solid: ct-slice-donut-solid !default;
$ct-class-grid: ct-grid !default;
$ct-class-grid-background: ct-grid-background !default;
$ct-class-vertical: ct-vertical !default;
$ct-class-horizontal: ct-horizontal !default;
$ct-class-start: ct-start !default;
$ct-class-end: ct-end !default;

// Container ratio
$ct-container-ratio: (1/1.618) !default;

// Text styles for labels
$ct-text-color: rgba(0, 0, 0, 0.4) !default;
$ct-text-size: 0.75rem !default;
$ct-text-align: flex-start !default;
$ct-text-justify: flex-start !default;
$ct-text-line-height: 1;

// Grid styles
$ct-grid-color: rgba(0, 0, 0, 0.2) !default;
$ct-grid-dasharray: 2px !default;
$ct-grid-width: 1px !default;
$ct-grid-background-fill: none !default;

// Line chart properties
$ct-line-width: 4px !default;
$ct-line-dasharray: false !default;
$ct-point-size: 10px !default;
// Line chart point, can be either round or square
$ct-point-shape: round !default;
// Area fill transparency between 0 and 1
$ct-area-opacity: 0.1 !default;

// Bar chart bar width
$ct-bar-width: 10px !default;

// Donut width (If donut width is to big it can cause issues where the shape gets distorted)
$ct-donut-width: 60px !default;

// If set to true it will include the default classes and generate CSS output. If you're planning to use the mixins you
// should set this property to false
$ct-include-classes: true !default;

// If this is set to true the CSS will contain colored series. You can extend or change the color with the
// properties below
$ct-include-colored-series: $ct-include-classes !default;

// If set to true this will include all responsive container variations using the scales defined at the top of the script
$ct-include-alternative-responsive-containers: $ct-include-classes !default;

// Series names and colors. This can be extended or customized as desired. Just add more series and colors.
$ct-series-names: (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) !default;
$ct-series-colors: (
  #d70206,
  #f05b4f,
  #f4c63d,
  #d17905,
  #453d3f,
  #59922b,
  #0544d3,
  #6b0392,
  #f05b4f,
  #dda458,
  #eacf7d,
  #86797d,
  #b2c326,
  #6188e2,
  #a748ca
) !default;

2、第一个应用

这部分文档是一个简易的应用项目,让开发人员能快速掌握chartist的使用方式,入门项目中会通过默认的基础配置实现一个线性图形解构,如果你有更复杂的应用需求,可以参考一下高级应用部分或者查看示例文档

(1) 概述

chartist提供了基础的api可以用于快捷构建应用,但是如果有个性化的定制需要,可以通过javascript格式的api完成颜色、线条等其他样式的处理

① 创建响应式图例

首先要明确响应式图例的含义,它不需要设置固定的宽度或者高度,而是通过按比例缩放的形式动态适应一些常见显示区域的比例,如4:3、3:2、16:9

备注:关于图例的比例

设计人员理解的比例和开发人员理解的比例存在一定的差异,如320x240300x200两个不同的比例,对于设计人员可能思考的更多的是4:3或者3:2的比例关系,而对于开发人员思考的更多的是具体的像素数据

chartist中开发人员不需要设置固定的宽度或者高度,直接将图表交给标签容易进行展示即可,如设置了.ct-golden-section样式的图表可以直接添加到设置了比例样式的标签容器中即可,如

<!-- 使用 3:4的比例创建图例 -->
<div class="ct-chart ct-perfect-fourth"></div>

<!-- 通过数据直接初始化图表即可,不需要再指定长度、宽度的数据 -->
<script>
var data = {
  // A labels array that can contain any sort of values
  // 一个包含展示内容的数组(可以包含任意类型的数据)
  labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  // Our series array that contains series objects or in this case series data arrays
  // 一个包含数据的数组(可以包含对象等其他格式的数据)
  series: [
    [5, 2, 4, 2, 0]
  ]
};

// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object.
// 第一个参数是一个选择器,用于创建对应的图表对象
// 第二个参数是需要处理的数据
new Chartist.Line('.ct-chart', data);
</script>

代码执行后,展示的图表数据

image.png

备注:一些常见的比例

容器样式Container Class 长宽比例Ratio
.ct-square 1
.ct-minor-second 15:16
.ct-major-second 8:9
.ct-minor-third 5:6
.ct-major-third 4:5
.ct-perfect-fourth 3:4
.ct-perfect-fifth 2:3
.ct-minor-sixth 5:8
.ct-golden-section 1:1.618
.ct-major-sixth 3:5
.ct-minor-seventh 9:16
.ct-major-seventh 8:15
.ct-octave 1:2
.ct-major-tenth 2:5
.ct-major-eleventh 3:8
.ct-major-twelfth 1:3
.ct-double-octave 1:4

② 创建固定维度图例

开发人员如果要创建具有固定的高度和宽度的图例,可以通过Chartist实例中添加相关选项配置即可

备注:此时可以省略指定长宽比例的样式名称.ct-perfect-fourth;即使指定也会被默认设定无效!

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./libs/chartist.min.css">
</head>

<body>
  <div class="ct-chart"></div>
  <script src="./libs/chartist.min.js"></script>
  <script>
    var data = {
      // A labels array that can contain any sort of values
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
      // Our series array that contains series objects or in this case series data arrays
      series: [
        [5, 2, 4, 2, 0]
      ]
    };

    // As options we currently only set a static size of 300x200 px. 
    // 设置固定的长宽比例
    // We can also omit this and use aspect ratio containers
    // as you saw in the previous example
    // 我们也可以省略这个固定配置就会得到长宽比例的图表
    // 参考上一个项目
    var options = {
      width: 300,
      height: 200
    };

    // Create a new line chart object where as first parameter we pass in a selector
    // that is resolving to our chart container element. The Second parameter
    // is the actual data object.
    new Chartist.Line('.ct-chart', data, options);
  </script>
</body>

</html>
image.png

③ 单页面多图例

如果需要在一个页面中创建多个图例进行展示,不推荐使用上述class样式名称的方式,而是推荐通过标签id属性进行图表容器的挂载匹配

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./libs/chartist.min.css">
</head>
<body>
  <div style="display: flex;">
    <div class="ct-chart" id="chart1"></div>
    <div class="ct-chart " id="chart2"></div>
  </div>

  
  <script src="./libs/chartist.min.js"></script>
  <script>
    // Initialize a Line chart in the container with the ID chart1
    new Chartist.Line('#chart1', {
      labels: [1, 2, 3, 4],
      series: [[100, 120, 180, 200]],
    }, {width: 400, height: 240});

    // Initialize a Line chart in the container with the ID chart2
    new Chartist.Bar('#chart2', {
      labels: [1, 2, 3, 4],
      series: [[5, 2, 8, 3]]
    }, {width: 300, height: 200});
  </script>
</body>
</html>

实现效果如图所示:

image.png

(2) 图例配置

Chartist图例提供了非常灵活的配置,几乎可以配置图例中展示的任何数据;它提供的默认的配置(参考官方API)中也提供了大量的预定义的配置信息供开发人员使用,实际应用时可以通过Chartist实例的配置选项覆盖默认配置

添加配置的折线图例

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./libs/chartist.min.css">
</head>

<body>
  <div class="ct-chart"></div>
  <script src="./libs/chartist.min.js"></script>
  <script>
    // Our labels and three data series
    // 一个图例中展示多套数据
    var data = {
      labels: ['第一周', '第二周', '第三周', '第四周', '第五周', '第六周'],
      series: [
        [5, 4, 3, 7, 5, 10],
        [3, 2, 9, 5, 4, 6],
        [2, 1, -3, -4, -2, 0]
      ]
    };

    // We are setting a few options for our chart and override the defaults
    // 给图例添加自定义配置,覆盖默认配置
    var options = {
      // 不展示坐标点
      // Don't draw the line chart points
      showPoint: false,
      // 不做平滑处理
      // Disable line smoothing
      lineSmooth: false,
      // X-Axis specific configuration
      axisX: {
        // 不展示网格
        // We can disable the grid for this axis
        showGrid: false,
        // 不展示标签提示
        // and also don't show the label
        showLabel: false
      },
      // Y-Axis specific configuration
      axisY: {
        // 偏移配置
        // Lets offset the chart a bit from the labels
        offset: 60,
        // The label interpolation function enables you to modify the values
        // used for the labels on each axis. Here we are converting the
        // values into million pound.
        // 通过函数设置指定展示的标记
        labelInterpolationFnc: function (value) {
          return '$' + value + 'm';
        }
      },
      width: 500,
      height: 300
    };

    // All you need to do is pass your configuration as third parameter to the chart function
    new Chartist.Line('.ct-chart', data, options);
  </script>
</body>

</html>

实现效果如图所示:

image.png

(3)响应式处理

网页视图的响应式设计一般都是基于媒体查询的,图例在不同的媒体设备上展示的效果可能也有差异;不过好在图例是在一个容器窗口中进行展示的,开发人员只需要对容器窗口进行媒体配置也可以实现多种不同媒体响应式的处理

① 覆盖默认配置

通过覆盖机制,让不同的媒体设备上的响应式处理变得比较简单,覆盖机制的优先级基于媒体查询顺序

下面的示例就是在不同的展示尺寸的设备上,让图例的尺寸、标签、条状图间距等进行调整的一种响应式场景

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./libs/chartist.min.css">
</head>

<body>
  <div class="ct-chart ct-minor-seventh"></div>
  <script src="./libs/chartist.min.js"></script>
  <script>
    var data = {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', '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: 15
    };

    // 响应式配置
    var responsiveOptions = [
      ['screen and (min-width: 641px) and (max-width: 1024px)', {
        // 屏幕尺寸641~1024 间距10像素
        seriesBarDistance: 10,
        axisX: {
          labelInterpolationFnc: function (value) {
            return value;
          }
        }
      }],
      ['screen and (max-width: 640px)', {
        // 屏幕尺寸<640 间距5像素
        seriesBarDistance: 5,
        // 屏幕尺寸<640 展示标签第一个字符
        axisX: {
          labelInterpolationFnc: function (value) {
            return value[0];
          }
        }
      }]
    ];

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

</html>

实现效果如图:可以缩放窗口查看效果

image.png

② 不同数据不同配置

有需求的情况下开发人员甚至可以给一张图例中的不同数据列添加不同的配置项,包括响应式配置

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./libs/chartist.min.css">
</head>

<body>
  <div class="ct-chart ct-minor-seventh"></div>
  <script src="./libs/chartist.min.js"></script>
  <script>
    // 参数1:选择器
    // 参数2:数据
    // 参数3:配置
    var chart = new Chartist.Line('.ct-chart', {
      // X方向显示标签内容
      labels: ['1', '2', '3', '4', '5', '6', '7', '8'],
      // Naming the series with the series object array notation
      // 数组的形式,设置多项命名数据列
      series: [{
        name: 'series-1',
        data: [5, 2, -4, 2, 0, -2, 5, -3]
      }, {
        name: 'series-2',
        data: [4, 3, 5, 3, 1, 3, 6, 4]
      }, {
        name: 'series-3',
        data: [2, 4, 3, 1, 4, 5, 3, 2]
      }]
    }, {
      fullWidth: true,
      // Within the series options you can use the series names
      // to specify configuration that will only be used for the
      // specific series.
      // 数据配置项中可以通过上面数组中的命名名称进行指定配置
      series: {
        'series-1': {
          // 阶梯线条
          lineSmooth: Chartist.Interpolation.step()
        },
        'series-2': {
          // 基本配置的线条
          lineSmooth: Chartist.Interpolation.simple(),
          // 显示包含区域
          showArea: true
        },
        'series-3': {
          // 不展示坐标点
          showPoint: false
        }
      }
    }, [
      // You can even use responsive configuration overrides to
      // customize your series configuration even further!
      // 可以通过命名名称,添加响应式配置覆盖默认配置
      ['screen and (max-width: 640px)', {
        series: {
          'series-1': {
            lineSmooth: Chartist.Interpolation.none()
          },
          'series-2': {
            lineSmooth: Chartist.Interpolation.none(),
            showArea: false
          },
          'series-3': {
            lineSmooth: Chartist.Interpolation.none(),
            showPoint: true
          }
        }
      }]
    ]);
  </script>
</body>

</html>

实现效果展示:调整窗口大小,响应式配置生效

image.png image.png

3、自定义样式

很多时候友好的界面对数据的有效展示非常重要,开发人员可以通过CSS样式提升数据图表友好性

(1) 定义默认名称

Chartist提供了一个高度定制的sass文件,允许开发人员可以自定义图表上展示的任意数据视图,包括数据视图、线条样式、线条宽度、线条颜色等等,如果你有sass相关的经验,强烈建议使用sass版本的Chartist进行开发

备注:关于默认配置

默认情况下Chartist自动生成的样式名称都是ct-series-a开头的,并且字母a会与每个数据a/b/c/d等一起迭代展示,如果需要处理特定数据的样式,就需要给相应的数据类名称创建特定的样式

① 线性图默认样式

/* Use this selector to override the line style on a given series */
.ct-series-a .ct-line {
  /* Set the colour of this series line */
  stroke: red;
  /* Control the thikness of your lines */
  stroke-width: 5px;
  /* Create a dashed line with a pattern */
  stroke-dasharray: 10px 20px;
}

/* This selector overrides the points style on line charts. Points on line charts are actually just very short strokes. This allows you to customize even the point size in CSS */
.ct-series-a .ct-point {
  /* Colour of your points */
  stroke: red;
  /* Size of your points */
  stroke-width: 20px;
  /* Make your points appear as squares */
  stroke-linecap: square;
}

② 条状图默认样式

/* Use this selector to override bar styles on bar charts. Bars are also strokes so you have maximum freedom in styling them. */
.ct-series-a .ct-bar {
  /* Colour of your bars */
  stroke: red;
  /* The width of your bars */
  stroke-width: 20px;
  /* Yes! Dashed bars! */
  stroke-dasharray: 20px;
  /* Maybe you like round corners on your bars? */
  stroke-linecap: round;
}

③ 饼状图默认样式

/* Pie charts consist of solid slices where you can use this selector to override the default style. */
.ct-series-a .ct-slice-pie {
  /* fill of the pie slieces */
  fill: hsl(120, 40%, 60%);
  /* give your pie slices some outline or separate them visually by using the background color here */
  stroke: white;
  /* outline width */
  stroke-width: 4px;
}

④ 圆环图默认样式

/* 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;
}

(2)图例上色案例

图例中数据线条的颜色展示是一个非常重要的核心样式,但是要达到外观和功能的分离,Chartist中并没有提供和颜色相关的配置选项,如果有必要的情况下需要开发人员通过自定义样式实现,避免造成后期维护困难

备注:Chartist默认提供了15中颜色给图例进行展示,开发人员如果只是覆盖其中的部分颜色,建议自定义样式实现

① 基本着色

代码操作:通过自定义样式名称,覆盖线形图中前两个数据的线条和坐标点的颜色

.ct-series-a .ct-line,
.ct-series-a .ct-point {
  stroke: blue;
}

.ct-series-b .ct-line,
.ct-series-b .ct-point {
  stroke: red;
}

上一个案例代码中,加入该自定义样式,展示效果如图所示:

image.png

② 动态着色

通过默认的预定义class名称进行数据列的颜色设置已经可以满足大部分场景,但是css的特性决定了对动态颜色设置并不是十分友好,那如果有要求要开发动态热力图或者动态处理折线数量应该怎么操作?

Chartist提供了一种事件驱动的动态图例方式,允许开发人员通过draw事件直接操作图例中的任意数据和样式,我们通过一个案例观察如何通过数据动态设置图例

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./libs/chartist.min.css">
</head>

<body>
  <div class="ct-chart ct-minor-seventh"></div>
  <script src="./libs/chartist.min.js"></script>
  <script>
    var count = 45;
    var max = 100;

    // Creating a bar chart with no labels and a series array with one series. 
    // For the series we generate random data with `count` elements and 
    // random data ranging from 0 to `max`.
    // 创建一个没有label展示标签和单列数据的条状图
    // 数据列随机产生count数量个0~max的随机数
    var chart = new Chartist.Bar('.ct-chart', {
      labels: Chartist.times(count),
      series: [
        Chartist.times(count).map(Math.random).map(Chartist.mapMultiply(max))
      ]
    }, {
      axisX: {
        showLabel: false
      },
      axisY: {
        onlyInteger: true
      }
    });

    // This is the bit we are actually interested in. By registering a callback for `draw` events, we can actually intercept the drawing process of each element on the chart.
    chart.on('draw', function (context) {
      // First we want to make sure that only do something when the draw event is for bars. Draw events do get fired for labels and grids too.
      if (context.type === 'bar') {
        // With the Chartist.Svg API we can easily set an attribute on our bar that just got drawn
        context.element.attr({
          // Now we set the style attribute on our bar to override the default color of the bar. By using a HSL colour we can easily set the hue of the colour dynamically while keeping the same saturation and lightness. From the context we can also get the current value of the bar. We use that value to calculate a hue between 0 and 100 degree. This will make our bars appear green when close to the maximum and red when close to zero.
          style: 'stroke: hsl(' + Math.floor(Chartist.getMultiValue(context.value) / max * 100) + ', 50%, 50%);'
        });
      }
    });
  </script>
</body>

</html>

实现效果如图所示:

image.png

4、高级应用

Chartist是一个非常灵活的图例库,在提供的基础api上允许开发人员可以自己实现一些其他扩展功能

上一篇下一篇

猜你喜欢

热点阅读