amCharts JavaScript Charts建立3D柱形圖

建立一個容器

咱們將這個容器命名爲「chartContainer」,參考如下代碼: javascript

<body>
    <div id="chartContainer" style="width: 640px; height: 400px;"></div>
</body>

引用JavaScript庫

在HEAD部分,引用amCharts JavaScript庫: html

<script src="js/amcharts.js" type="text/javascript"></script>

添加數據

引用一組JavaScript對象: java

<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控制數據對象的字段。 ide

var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";

接下來咱們須要添加一個graph到圖表中。一個圖表能夠有多個graph,但本例咱們只用一個graph。指定valueField,設置type字段爲「column」,這樣咱們就能夠建立一個柱狀圖了。 spa

var graph = new AmCharts.AmGraph();
graph.valueField = "visits"
graph.type = "column";
chart.addGraph(graph);

最後調用 write()方法將圖表寫入 「chartContainer」 中: code

chart.write('chartContainer');

效果圖: htm

 

自定義軸標籤

在上圖中,X軸上並未標出每一列的名稱,這樣確定不行,那咱們就調整categoryAxis的gridCount屬性: 對象

var catAxis = chart.categoryAxis;
catAxis.gridCount = chartData.length;

會獲得如下結果: ip

 

這些標籤都擠到一塊兒了,那咱們能夠嘗試用categoryAxis的labelRotation屬性將標籤旋轉90度: it

var catAxis = chart.categoryAxis;
catAxis.gridCount = chartData.length;
catAxis.labelRotation = 90;


結果標籤字段被截取掉了一部分,那須要設置圖表的margins:

chart.marginTop = 15;
chart.marginLeft = 55;
chart.marginRight = 15;
chart.marginBottom = 80;

這樣就沒有問題了:


填充顏色&3D效果

首先填充柱子的顏色並隱藏它們的邊框:

graph.lineAlpha = 0;
graph.fillAlphas = 0.8;

而後將平面的柱狀圖變爲3D效果,depth3D屬性控制柱子的深度和角度,也就是3D方向:

chart.angle = 30;
chart.depth3D = 15;

終於,3D柱狀圖的效果就出來了:

相關文章
相關標籤/搜索