jubi avatar

使用Chartjs创建柱形图/Chartjs video tutorial:Bar Chart

jubi

Published: 11 Jan 2018 › Updated: 11 Jan 2018使用Chartjs创建柱形图/Chartjs video tutorial:Bar Chart

使用Chartjs创建柱形图/Chartjs video tutorial:Bar Chart

DQmbgzru4YUCtQnwiZkMBQHEzTxCUTzbUn5tSytrWUeukos_副本_副本_副本.jpg

Summary:
Bar Chart is the most commonly used chart,Today I'll show you how to use chartjs to create a bar chart.
柱形图是我们平常使用最多的图表形式之一,通常我们都是使用execl去生成,但是不美观,且不具备扩展性。今天我将介绍如何使用Chartjs,快速都创建一个柱形图。下面请先看视频教程:

视频中的柱形图样例为:
360截图20180111231216701.jpg
其代码部分为:

{
"type":"bar",
"data":{
"labels":[
"1",
"2",
"3",
"4",
"5",
"6"
],
"datasets":[
{
"label":"votes",
"data":[
12,
19,
3,
5,
2,
3
],
"backgroundColor":[
"rgba(225,99,132,0.2)",
"rgba(54,126,235,0.2)",
"rgba(225,206,86,0.2)",
"rgba(75,192,192,0.2)",
"rgba(153,102,225,0.2)",
"rgba(225,159,64,0.2)"
],
"borderColor":[
"rgba(255,99,132,1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
 "rgba(255, 159, 64, 1)"
 ],
 "borderWidth":1
 }
 ]
 },
 "options":{}
 }

1.使用的开发工具

很明显透过上述代码可以看出,没有进行js定义,没有html,也就是这仅仅是对数据,样式进行简单处理的代码。chartjs可以说是一个图表引擎,任何工具网站都可以搭载它,如果我们在已经搭载它的工具上面创建图表,就可以不需要考虑调用js等问题,直接通过书写chartjs的相关代码就可以实现生成图表。本次演示的工具是Markdown plus,当然也有网页版本,其网址为:http://mdp.tylingsoft.com/

2.语法格式

因为我们是借助于一款markdown编辑器的扩展功能实现chartjs图表创建,所以我们的代码输入仍然需要遵循markdown的格式,如下:

····chart
chartjs
····   

柱形图主要需要设置的是,标签名,标签数据,背景颜色,边框颜色,边框宽度这五个部分。下面我将分别说明:

设置标签名,也就是每个柱形图的名称,名称用“”括起来,之间用,隔开。

"labels":[
"1",
"2",
"3",
"4",
"5",
"6"
],

每个标签的数据,这里的label指的是图例

"label":"votes",
"data":[
12,
19,
3,
5,
2,
3
],

背景颜色、边框颜色

"backgroundColor":[
"rgba(225,99,132,0.2)",
"rgba(54,126,235,0.2)",
"rgba(225,206,86,0.2)",
"rgba(75,192,192,0.2)",
"rgba(153,102,225,0.2)",
"rgba(225,159,64,0.2)"
],
"borderColor":[
"rgba(255,99,132,1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
 "rgba(255, 159, 64, 1)"
 ],

这里使用的rgba,是rgb的扩展,最后面一个参数是颜色的透明程度。

边框粗细

 "borderWidth": 1

下面我用最简单的2个标签柱形图作为例子:
360截图20180111232843292.jpg
代码如下:

{
"type":"bar",
"data":{
"labels":[
"1",
"2",
"3"
],
"datasets":[
{
"label":"votes",
"data":[
12,
19,
3
],
"backgroundColor":[
"rgba(225,99,132,0.2)",
"rgba(54,126,235,0.2)",
"rgba(225,206,86,0.2)"
],
"borderColor":[
"rgba(255,99,132,1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)"
 ],
 "borderWidth":1
 }
 ]
 },
 "options":{}
 }

标签数量,数据数量,以及背景颜色,边框颜色的数量是一致的。具有对应关系,所以在输入的时候,要注意对应,另外在每组数据的最后一个数据后面,不需要添加逗号。

谢谢阅读本次教程,谢谢。



Posted on Utopian.io - Rewarding Open Source Contributors

Leave 使用Chartjs创建柱形图/Chartjs video tutorial:Bar Chart to:

Written by

Read more #utopian-io posts


Best Posts From jubi

We have not curated any of jubi's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From jubi