create account

Tutorial #2 G2 (The Grammar of Graphics) - Create Pie Chart by gentlemanoi

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

#### What Will I Learn?
- How to create pie chart using g2
- Example codes using g2

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

#### Difficulty
- Intermediate

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

###### Introduction
In this tutorial, we will create a simple pie chart that will display the sample number of utopian contributions.

Pie chart is a circular graph that represents a statistical data. This graph is divided into slices which illustrate the numerical proportion. The arc length of each slices is proportional to the number of quantity it represents. Using pie chart is a way of summarizing a set of categorical data or shows percentage distribution.

###### Import G2 js
To start, we have to import first the G2 library in our application. We can use a CDN or dowload/copy+paste the file into our local machine.

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

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

###### Create pie chart
So let's start creating our pie chart.
- First, we need to initialize the data in `JSON` format. We can use any data which will be displayed in our pie chart. For this tutorial, we will create a pie chart that will display the percentage of each Utopian contributions.
```
var data = [
        { contribution: 'Development', count: 78 },
        { contribution: 'Bug Hunting', count: 96 },
        { contribution: 'Graphics', count: 66 },
        { contribution: 'Analysis', count: 55 },
        { contribution: 'Visibility', count: 103 },
        { contribution: 'Documentation', count: 58 },
        { contribution: 'Tutorials', count: 121 },
        { contribution: 'Video Tutorials', count: 87 },
        { contribution: 'Copywriting', count: 52 },
        { contribution: 'Blog Post', count: 51   },
        { contribution: 'Suggestion', count: 125 },
 ];
```

- Then, initialize the G2 chart with the element or container where we want to display the chart and we can also set the height and the width.
```
var chart = new G2.Chart({
        container: 'canvas',
        height: 700,
        width: 850
 });
```

- Pass the `JSON` data to the G2 chart as the source data.
```
chart.source(data);
```

- Use `coord` to set the Cartesian coordinate that we will use. There are four types of coord: rect, polar, theta, and helix. For circular graphs we will use the theta coord type.
```
chart.coord('theta');
```

- Next, set the position of the interval that will determine what attribute of data we will use to illustrate the percentage of each slices. Instead of `interval` we will use `intervalStack` for circular graphs. And also we will set the color and label of each slices. For the color, we will just set what attribute of object that we need to emphasize.
```
chart.intervalStack().position('count').color('contribution')
        .label('contribution*count', {
          content(name, value) {
            return name + ':' + value;
          }
  });
```
For the label, we have to pass the attributes that we want to display and use the content function that will return the label as a string.

- Lastly, RENDER the pie chart.
```
chart.render();
```

Result:
<center>
![g2.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1521133242/bl83ylzgpdb4qpaqy5jk.png)
</center>

[Demo](https://jsfiddle.net/mervinvillaceran/h03hzxwf/)

#### Curriculum
- [Tutorial #1 G2 (The Grammar of Graphics) - Create Bar Chart](https://utopian.io/utopian-io/@gentlemanoi/tutorial-1-g2-the-grammar-of-graphics-create-bar-chart)
    

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@gentlemanoi/tutorial-2-g2-the-grammar-of-graphics-create-pie-chart">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , ,
properties (23)
authorgentlemanoi
permlinktutorial-2-g2-the-grammar-of-graphics-create-pie-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"],"users":["gentlemanoi"],"links":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1521133242/bl83ylzgpdb4qpaqy5jk.png","https://jsfiddle.net/mervinvillaceran/h03hzxwf/","https://utopian.io/utopian-io/@gentlemanoi/tutorial-1-g2-the-grammar-of-graphics-create-bar-chart"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1521133242/bl83ylzgpdb4qpaqy5jk.png"],"moderator":{"account":"scipio","time":"2018-03-17T13:16:50.408Z","flagged":true,"reviewed":false,"pending":false},"questions":[],"score":null}
created2018-03-15 17:26:36
last_update2018-03-17 13:16:51
depth0
children1
last_payout2018-03-22 17:26:36
cashout_time1969-12-31 23:59:59
total_payout_value3.148 HBD
curator_payout_value1.378 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,002
author_reputation5,059,544,469,757
root_title"Tutorial #2 G2 (The Grammar of Graphics) - Create Pie Chart"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,635,574
net_rshares1,589,176,009,523
author_curate_reward""
vote details (11)
@scipio ·
$0.39
Your contribution cannot be approved because it does not follow the [Utopian Rules](https://utopian.io/rules).

Explanation: again, you didn't explain anything just dropped in code.

For example:
```
Use coord to set the Cartesian coordinate that we will use. There are four types of coord: rect, polar, theta, and helix. For circular graphs we will use the theta coord type.
```

^^^ Why use `theta`? What do all these four coordinate types do?

And:
```
Instead of interval we will use intervalStack for circular graphs.
```

^^^ Why? What does `interval()` do? What does `intervalStack()` do?

Other than this, you again just imported the g2.js CDN in your `<head>` section, dropped in a dummy data array (that's fine), instantiated a `G2.Chart()` object and dropped in the data.



You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
👍  ,
properties (23)
authorscipio
permlinkre-gentlemanoi-tutorial-2-g2-the-grammar-of-graphics-create-pie-chart-20180317t132027115z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-17 13:20:27
last_update2018-03-17 13:20:27
depth1
children0
last_payout2018-03-24 13:20:27
cashout_time1969-12-31 23:59:59
total_payout_value0.292 HBD
curator_payout_value0.094 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length903
author_reputation34,229,826,851,736
root_title"Tutorial #2 G2 (The Grammar of Graphics) - Create Pie Chart"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id44,951,858
net_rshares111,259,729,967
author_curate_reward""
vote details (2)