create account

Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart by gentlemanoi

View this thread on: hive.blogpeakd.comecency.com
· @gentlemanoi · (edited)
$71.83
Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart
<center>
![g2.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521033721/jm9ihxtiwng0cdwggzgi.png)
</center>

#### What Will I Learn?
- How to use G2 js (The grammar of graphics)
- How to create bar chart using g2
- Example codes using g2

#### Requirements
- Knowledge of HTML
- Knowledge of JavaScript

#### Difficulty
- Intermediate

#### Tutorial Contents
- Introduction
- Import G2 js
- Create bar chart

###### Introduction
G2, The Grammar of Graphics, is a data-driven visual language developed by the [AntV Team](https://github.com/antvis). This javascript library can create different kinds of charts and graphs with a high level of usability and scalability and this will render your charts/graphs using canvas. G2 is a great tool to help developers for data visualization on their applications. In this tutorial, we will cover on how create a bar chart.

*"With G2, users can describe the visual appearance of a visualization just by one statement."* - AntV Team

###### Import 
Before we can use the library, we have to import a javascript file on our application. We can just use a CDN or download the file in our local machine.

CDN: https://gw.alipayobjects.com/os/antv/assets/g2/3.0.5-beta.5/g2.min.js

Then, add the javascript file in our application using the  script tag.
```
<script src="https://gw.alipayobjects.com/os/antv/assets/g2/3.0.5-beta.5/g2.min.js"></script>
```

###### Create Bar Chart
In this tutorial, we will create a bar chart that will display the number of users per age.

- First, we need to get/initialize the data for the bar chart.  For that, we will just create a sample array of users with their corresponding age.
```
var data = [
		{"name" : "John", "age" : 20},
		{"name" : "Mary", "age" : 23},
		{"name" : "Susan", "age" : 22},
		{"name" : "Bernard", "age" : 19},
		{"name" : "Joe", "age" : 20},
		{"name" : "Elen", "age" : 22},
		{"name" : "George", "age" : 22},
		{"name" : "Michael", "age" : 21},
];
```

- Then, we have to group this array of users by age with a new count attribute. In this example, we will use the data-set library by AntV. But you can also use a vanilla javascript function to group the users by age.

- To use the data-set library, we have to import another javascript file.
```
<script src="https://gw.alipayobjects.com/os/antv/assets/data-set/0.8.5/data-set.min.js"></script>
```
- Then use the library to transform the data.
```
var dataSet = new DataSet();
var newData= dataSet.createView('test')
	        .source(data)
	        .transform({
	              as: [ 'count' ],
	              groupBy: [ 'age' ],
	              type: 'aggregate'
            });
```
- Or you can use vanilla javascript:
```
var result = [];

data.forEach(function (element) {
	   var existingElement = result.filter(function (item) {
	          return item.age === element.age;
	    })[0];

	    if (existingElement) {
	         existingElement.count++;
	     } else {
	           var newData = {
	            	age : element.age,
	            	count : 1
	            }
	            result.push(newData);
	       }
});
```
- Before we can create the chart, we have to create first an html container where we can display it.
```
<div id="container"></div>
```
- Then, we can initialize/create the G2 chart.
```
var chart = new G2.Chart({
		  container: 'container', // container ID
		  width : 600, // width of chart
		  height : 600 // height of chart
});
```
- After that, we have to set the data source for the chart.
```
chart.source(newData);
```
- Then, we have to set the syntax for the position of the columns or what should be displayed on x and y axis of the chart.
```
chart.interval().position('age*count'); // (x*y)
``` 
- Lastly, RENDER the bar chart.
```
chart.render();
```
Result:
<center>
![g2.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521037872/nkcnj7crabbwtfhib9x5.png)
</center>
    
[Demo](https://jsfiddle.net/mervinvillaceran/dmo0bjt5/)

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@gentlemanoi/tutorial-1-g2-the-grammar-of-graphics-create-bar-chart">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorgentlemanoi
permlinktutorial-1-g2-the-grammar-of-graphics-create-bar-chart
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":59737212,"name":"g2","full_name":"antvis/g2","html_url":"https://github.com/antvis/g2","fork":false,"owner":{"login":"antvis"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","utopian-io","tutorial","g2"],"links":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1521033721/jm9ihxtiwng0cdwggzgi.png","https://github.com/antvis","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521037872/nkcnj7crabbwtfhib9x5.png","https://jsfiddle.net/mervinvillaceran/dmo0bjt5/"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1521033721/jm9ihxtiwng0cdwggzgi.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1521037872/nkcnj7crabbwtfhib9x5.png"],"moderator":{"account":"portugalcoin","time":"2018-03-15T21:47:22.513Z","reviewed":true,"pending":false,"flagged":false},"questions":[{"question":"Is the project description formal?","answers":[{"value":"Yes it’s straight to the point","selected":true,"score":10},{"value":"Need more description ","selected":false,"score":5},{"value":"Not too descriptive","selected":false,"score":0}],"selected":0},{"question":"Is the language / grammar correct?","answers":[{"value":"Yes","selected":true,"score":20},{"value":"A few mistakes","selected":false,"score":10},{"value":"It's pretty bad","selected":false,"score":0}],"selected":0},{"question":"Was the template followed?","answers":[{"value":"Yes","selected":true,"score":10},{"value":"Partially","selected":false,"score":5},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is there information about the additional frameworks?","answers":[{"value":"Yes, everything is explained","selected":true,"score":5},{"value":"Yes, but not enough","selected":false,"score":3},{"value":"No details at all","selected":false,"score":0}],"selected":0},{"question":"Is there code in the tutorial?","answers":[{"value":"Yes, and it’s well explained","selected":true,"score":5},{"value":"Yes, but no explanation","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial explains technical aspects well enough?","answers":[{"value":"Yes, it teaches how and why about technical aspects","selected":true,"score":5},{"value":"Yes, but it’s not good/enough","selected":false,"score":3},{"value":"No, it explains poorly","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial general and dense enough?","answers":[{"value":"Yes, it’s general and dense","selected":false,"score":5},{"value":"Kinda, it might be more generalized","selected":true,"score":3},{"value":"No, it’s sliced unnecessarily to keep part number high","selected":false,"score":0}],"selected":1},{"question":"Is there an outline for the tutorial content at the beginning of the post","answers":[{"value":"Yes, there is a well prepared outline in “What will I learn?” or another outline section","selected":true,"score":5},{"value":"Yes, but there is no proper listing for every step of the tutorial or it’s not detailed enough","selected":false,"score":3},{"value":"No, there is no outline for the steps.","selected":false,"score":0}],"selected":0},{"question":"Is the visual content of good quality?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Yes, but bad quality","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is this a tutorial series?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Yes, but first part","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial post structured?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Not so good","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0}],"score":50}"
created2018-03-14 14:56:57
last_update2018-03-15 21:47:24
depth0
children4
last_payout2018-03-21 14:56:57
cashout_time1969-12-31 23:59:59
total_payout_value49.906 HBD
curator_payout_value21.925 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,134
author_reputation5,059,544,469,757
root_title"Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,390,054
net_rshares27,750,430,058,304
author_curate_reward""
vote details (21)
@portugalcoin ·
$1.04
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
👍  
properties (23)
authorportugalcoin
permlinkre-gentlemanoi-tutorial-1-g2-the-grammar-of-graphics-create-bar-chart-20180315t214730703z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-15 21:47:33
last_update2018-03-15 21:47:33
depth1
children2
last_payout2018-03-22 21:47:33
cashout_time1969-12-31 23:59:59
total_payout_value0.780 HBD
curator_payout_value0.258 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation598,828,312,571,988
root_title"Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,669,854
net_rshares297,587,626,327
author_curate_reward""
vote details (1)
@gentlemanoi ·
Hi @portugalcoin Thank you!
properties (22)
authorgentlemanoi
permlinkre-portugalcoin-re-gentlemanoi-tutorial-1-g2-the-grammar-of-graphics-create-bar-chart-20180316t014535750z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["portugalcoin"],"app":"steemit/0.1"}
created2018-03-16 01:45:45
last_update2018-03-16 01:45:45
depth2
children0
last_payout2018-03-23 01:45:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length27
author_reputation5,059,544,469,757
root_title"Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,700,142
net_rshares0
@utopian.tip ·
Hey @portugalcoin, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!
👍  
properties (23)
authorutopian.tip
permlinkre-re-gentlemanoi-tutorial-1-g2-the-grammar-of-graphics-create-bar-chart-20180315t214730703z-20180315t221947
categoryutopian-io
json_metadata""
created2018-03-15 22:19:48
last_update2018-03-15 22:19:48
depth2
children0
last_payout2018-03-22 22:19:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length162
author_reputation238,310,597,885
root_title"Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,674,128
net_rshares2,471,375,176
author_curate_reward""
vote details (1)
@utopian-io ·
### Hey @gentlemanoi I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-gentlemanoi-tutorial-1-g2-the-grammar-of-graphics-create-bar-chart-20180316t205425029z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-16 20:54:27
last_update2018-03-16 20:54:27
depth1
children0
last_payout2018-03-23 20:54:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,087
author_reputation152,955,367,999,756
root_title"Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,826,898
net_rshares0