我们将这个容器命名为“chartContainer”,参考以下代码:
<body> <div id="chartContainer" style="width: 640px; height: 400px;"></div> </body>
在HEAD部分,引用amCharts JavaScript库:
<script src="js/amcharts.js" type="text/javascript"></script>
引用一组JavaScript对象:
<script type="text/javascript"> var chartData = [{ country: "USA", visits: 4252 }, { country: "China", visits: 1882 }, { country: "Japan", visits: 1809 }, { country: "Germany", visits: 1322 }, { country: "UK", visits: 1122 }, { country: "France", visits: 1114 }, { country: "India", visits: 984 }, { country: "Spain", visits: 711 }, { country: "Netherlands", visits: 665 }, { country: "Russia", visits: 580 }, { country: "South Korea", visits: 443 }, { country: "Canada", visits: 441 }, { country: "Brazil", visits: 395 }, { country: "Italy", visits: 386 }, { country: "Australia", visits: 384 }, { country: "Taiwan", visits: 338 }, { country: "Poland", visits: 328}]; </script>
首先我们需要为图表创建一个AmCharts.AmSerialChart对象,设置它的dataProvider和categoryField属性。 顾名思义,dataProvider用于指定图表的数据源,categoryField控制数据对象的字段。
var chart = new AmCharts.AmSerialChart(); chart.dataProvider = chartData; chart.categoryField = "country";
接下来我们需要添加一个graph到图表中。一个图表可以有多个graph,但本例我们只用一个graph。指定valueField,设置type字段为“column”,这样我们就可以创建一个柱状图了。
var graph = new AmCharts.AmGraph(); graph.valueField = "visits" graph.type = "column"; chart.addGraph(graph);
最后调用 write()方法将图表写入 “chartContainer” 中:
chart.write('chartContainer');
效果图:
在上图中,X轴上并未标出每一列的名称,这样肯定不行,那我们就调整categoryAxis的gridCount属性:
var catAxis = chart.categoryAxis; catAxis.gridCount = chartData.length;
会得到以下结果:
这些标签都挤到一起了,那我们可以尝试用categoryAxis的labelRotation属性将标签旋转90度:
var catAxis = chart.categoryAxis; catAxis.gridCount = chartData.length; catAxis.labelRotation = 90;
结果标签字段被截取掉了一部分,那需要设置图表的margins:
chart.marginTop = 15; chart.marginLeft = 55; chart.marginRight = 15; chart.marginBottom = 80;
这样就没有问题了:
首先填充柱子的颜色并隐藏它们的边框:
graph.lineAlpha = 0; graph.fillAlphas = 0.8;
然后将平面的柱状图变为3D效果,depth3D属性控制柱子的深度和角度,也就是3D方向:
chart.angle = 30; chart.depth3D = 15;
终于,3D柱状图的效果就出来了: