如何使用bootstrap创建图表
Bootstrap中的图表是一种用于数据可视化的图形表示,其中的数据由符号表示。在Bootstrap的帮助下,可以创建各种类型的图表,如条形图、折线图、饼图、甜甜圈图等。换句话说,我们可以说图表是一种类型的图或图形,它组织和表示一组数字或定性的数据。
例子1:我们通过使用bootstrap和JavaScript来创建一个线形图。在这个例子中,我们使用chart.js文件来创建一个图表。数据是根据图表的类型来创建的。下面这个图表的类型是 “线”,有两个不同的数据,都是工作时间和自由时间。
<html>
<link
rel=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
type="text/css"
/>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script
src=
"https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"
type="text/javascript"
></script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script>
<style>
.container {
width: 70%;
margin: 15px auto;
}
body {
text-align: center;
color: green;
}
h2 {
text-align: center;
font-family: "Verdana", sans-serif;
font-size: 30px;
}
</style>
<body>
<div class="container">
<h2>Line Chart</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
],
datasets: [
{
label: "work load",
data: [2, 9, 3, 17, 6, 3, 7],
backgroundColor: "rgba(153,205,1,0.6)",
},
{
label: "free hours",
data: [2, 2, 5, 5, 2, 1, 10],
backgroundColor: "rgba(155,153,10,0.6)",
},
],
},
});
</script>
</html>
输出:
工作时间和自由时间折线图
实例2:在下面的例子中,我们通过使用bootstrap和JavaScript创建了一个甜甜圈图表。在这个例子中,我们也使用了chart.js文件来创建一个甜甜圈图表。 甜甜圈图是饼图的修改版,中间的区域被剪掉了。
<html>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src=
"https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.js"></script>
<link
rel="stylesheet"
href=
"https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css"
/>
<link
rel=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
type="text/css"
/>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js">
</script>
<style>
body {
text-align: center;
color: green;
}
h2 {
text-align: center;
font-family: "Verdana", sans-serif;
font-size: 40px;
}
</style>
<body>
<div class="col-xs-12 text-center">
<h2>Donut Chart</h2>
</div>
<div id="donut-chart"></div>
<script>
var chart = bb.generate({
data: {
columns: [
["Blue", 2],
["orange", 4],
["green", 3],
],
type: "donut",
onclick: function (d, i) {
console.log("onclick", d, i);
},
onover: function (d, i) {
console.log("onover", d, i);
},
onout: function (d, i) {
console.log("onout", d, i);
},
},
donut: {
title: "70",
},
bindto: "#donut-chart",
});
</script>
</body>
</html>
输出:
Doughnut chart