How the chart control uses JavaScript to create a Venn diagram

AnyChart is a chart control based on JavaScript (HTML5). Use AnyChart control to create cross-browser and cross-platform interactive charts and gauges. AnyChart charts are currently used by many well-known large companies and can be used in dashboards, reports, data analysis, statistics, finance and other fields.

AnyChar HTML5 charts are highly customizable and highly compatible. With pure JavaScript API, AnyChart chart built-in client data real-time update, multi-level drill down area and specific parameter update. The powerful theme engine allows you to have a unique presentation experience through a series of charts, while PDF and image output can produce book-quality printed documents.

Huidu.com free click to download the latest version of AnyChart

How the chart control uses JavaScript to create a Venn diagram

Venn diagram is a form of data visualization that uses shapes, usually circles, to show the relationship between groups of things. In this chart type, overlapping areas show common points, and non-overlapping circles show features that are not shared.

The Venn diagrams introduced by the British mathematician, logician and philosopher John Venn are also called set diagrams or logical diagrams because they show the possible logical relationships between different set elements. When drawing this type of chart, we are likely to deal with two or three overlapping circles, because having just one circle would be boring, and having four or more circles would quickly become very complicated.

These diagrams are not only a good visual concept, but also provide a good opportunity to represent qualitative data and some graphical humor. Basically, they are easy to build and use. I will tell you right away!

Read this tutorial to learn how to easily create a visually appealing and informative Venn diagram for your website or application with the help of JavaScript. All the code used and demonstrated in this tutorial is free to use.

During the ongoing coronavirus epidemic, working from home and avoiding eating outside, many of us have become amateur cooks. So let's use the JS-based Venn diagram to find out which formula is best to try in the working day-this will be a delightful use case!

Venn diagram will be developed

Before starting, I decided to stimulate your interest to provide an excellent data visualization and learning experience, and to show you how the final interactive JavaScript Venn diagram will look.
How the chart control uses JavaScript to create a Venn diagram

4 simple steps for basic JS Venn diagram

Venn diagrams are an enjoyment for visualizers and audiences. They provide great value and quick insight, while being easy to make and understand.

Let us see how to make a Venn diagram using JavaScript (HTML5). This may not be as simple as using different colored sketch pens to create circles on a napkin (maybe you can compare dogs and cats!).

In fact, you should follow the following 4 steps to build pretty JavaScript charts in almost any form, including Venn diagrams:
Create an HTML page for the chart.
Include the necessary JavaScript files.
adding data.
Write JS code for this graph.

1. Create an HTML page

Create a basic HTML page with block-level elements on which the Venn diagram will be rendered. This div element will save the chart and assign it a unique ID for future reference.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Venn Diagram</title>
<style type="text/css">
html,
body,
#container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
The width and height of the container are set to 100% for the chart Fill the entire screen. You can set other values ​​as needed to change the size of the graph.

2. Include the necessary JavaScript files

To create a JavaScript chart, you must link the appropriate JS script that will be used to develop it. These files must be contained within the <head> of the <script> tag in the HTML page section.

Feel free to choose the JS library for data visualization, because there are many libraries and this method is very versatile. In this tutorial, I will use AnyChart. It is a flexible and powerful JavaScript chart library, which makes it easy and fast to visualize data in robust graphs, so even beginners can. For Venn diagrams, we only need the core library modules required by all diagrams, and the dedicated modules used to create this specific diagram type.

You can download the required script and add it to the HTML page, or include a CDN link (for simplicity, we will do this here).
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Venn Diagram</title>
<script src=" https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min. js"></script> ;
<script src=" https://cdn.anychart.com/releases/8.9.0/js/anychart-venn.min.js"></script> ;
<style type=" text/css">
html,
body,
#container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container"> </div>
<script>


</body>
</html>
Note: We have added a script tag to the body where we will write the code to create the chart.

3. Add data

Data is the element that makes up the chart, so it is an important aspect of visualization. One of the great advantages of AnyChart is that it provides a variety of ways to add data. In this Venn diagram, we are using simple data, so we can include the data directly into the page.

Each chart presents data in a specific form, so it is important to ensure that the data is captured in a way that makes sense for the Venn diagram. This is very intuitive, so no need to worry.

Our data is about three aspects of information considered when choosing a recipe to try while working from home. A perfect formula is a formula with all three beneficial properties.

We list the 3 attributes considered as 3 data points and the intersection of 2 combinations and all 3 other individual data points.

Venn diagrams accept data arrays, so we construct the data in the same way.
data = [
{
x:'A',
value: 100,
name:'TIME \n Can be quickly made'
},
{
x:'B',
value: 100,
name:'INGREDIENTS \n Key elements available'
},
{
x:'C',
value: 100,
name:'COMPLEXITY \n Manageable level'
},
{
x: ['A','C'],
value: 25,
name:'Add to \n wishlist'
},
{
x: ['A','B'],
value: 25,
name:'Possibility \n of disaster'
},
{
x: ['B','C'],
value: 25,
name:'Try on a \n holiday'



value: 25,
name:'The perfect \n recipe'
}
]
Give the data point a value to indicate the amount of overlap and non-overlap. Since our data is qualitative, we assign the same value to each overlapping part. The name indicates the description of each data point. \nThe symbol seen in the description is a newline character, insert a newline character.

4. Write the JS code of Venn diagram

Now that everything is ready, we can prepare a basic Venn diagram with just a few lines of code.

All JavaScript code is placed in the <script> tag in the body of the HTML page. The first thing we need to do is to add a function that contains all the code to ensure that the code can only be executed after the page is ready.
<script type="text/javascript">
anychart.onDocumentReady(function() {
// All the code for drawing the chart will come here
});
</script>
Next, we add data and use that data to create a chart. Then, we set the container to reference the previously added HTML elements and draw the chart.
anychart.onDocumentReady(function () {
var data = [{data}];

// create friend diagram
var chart = anychart.venn (data);

// set container id for the chart
chart.container('container');

// initiate chart drawing
chart.draw();
}
We drew the Venn diagram, but we only added two lines of code to give the diagram a title, and set the label format to represent the intersecting data text instead of the value, because this It is more meaningful to our subjective data.
// set chart title
chart.title('The perfect recipe to try while working from home');

// set labels settings
chart.labels().format('{%Name}');
Customize Venn Diagram (make it better)
AnyChart library provides many options to adjust the appearance of data visualization. No matter what you do, there is always room for improvement. We can definitely change some of the content in the JS Venn diagram to make it more attractive, highlight certain points, add features to better understand the data, or just improve Appearance to suit our taste!

The easiest way to change the appearance of data is to try the various color themes provided by AnyChart. Just add the required theme to the top of the page, and then reference it in the code to complete.
<script src=" https://cdn.anychart.com/releases/8.9.0/themes/pastel.min.js"></script> ;

// set chart theme
anychart.theme('pastel');
Let's take a look at some other quick changes in this tutorial: the
overall chart appearance has improved.
Custom color for each data point.
Font change.
Special effect.

1. Improved overall appearance

We will make some small changes here and here to improve the visualization of the Venn diagram. Once again, you will see how easy it is to make these changes.

Since our Venn diagram displays the data point text on the chart, we don't actually need a legend.
// disable legend
chart.legend(false);
Then, let's add a stroke to the circle to make the intersecting area stand out.
// set chart stroke
chart.stroke('1 #fff');
and modify the size, style and position of the text to enhance the title and label.
// set chart title
chart
.title()
.enabled(true)
.fontSize(24)
.padding({ bottom: 25 })
.text("The perfect recipe to try while working from home");

// set labels settings
chart
.labels()
.fontSize(14)
.fontColor("#5e6469")
.hAlign("center")
.vAlign("center")
.fontWeight("500")
.format("{%Name}");

// set intersections labels settings
chart
.intersections()
.labels()
.fontStyle("italic")
.fontColor("#fff")
.format("{%Name}");

2. Custom color for each data point

When we want to use a different color for each data point, the best way is to add the color attribute to the data. In AnyChart, we can not only specify the color of each area, but also specify the color when hovering and selecting these areas.

Let's add normal, hover, and selected attributes to the data, and specify the fill color and opacity.

This is an example of data point A:
{
x:'A',
value: 100,
name:'TIME \n Can be quickly made',
normal: {fill: "#8ecafb 0.7"},
hovered: {fill: "# 8ecafb 1"},
selected: {fill: "#8ecafb 1"}
}

3. Font changes

We can use existing fonts or add Google fonts as described here. We just need to link the style sheet of the Google fonts we want to use at the top of the page, and then specify the font family if we want to apply it anywhere.
<link href=" https://fonts.googleapis.com/css2?family=Roboto:ital@0;1&display=swap "rel="stylesheet">
// add this in the code
.fontFamily('Roboto, sans- serif')

4. Some special effects

To add interest to our JavaScript Venn diagram, let's add texture fill in the intersection area and add some interesting text to the diagram tooltip.

Since the tooltip text and texture fill color will be specific to each data point, we will include them in the data.

Check out all these customized final interactive JavaScript based Venn diagrams! For your convenience, the complete code is located below the embedded interactive graphics. <!DOCTYPE html> <html> <head>
























<title>JavaScript Venn Diagram</title>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js"></script>;
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-venn.min.js"></script>;
<script src="https://cdn.anychart.com/releases/8.9.0/themes/pastel.min.js"></script>;
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital@0;1&display=swap" rel="stylesheet">
<style type="text/css">
html,
body,
#container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>

anychart.onDocumentReady(function () {
  // set chart theme
  anychart.theme('pastel');

  var data = [
    {
      x: 'A',
      value: 100,
      name: 'TIME \n Can be quickly made',
      tooltipTitle: 'TIME \n Can be quickly made',
      normal: {fill: "#8ecafb 0.7"},
      hovered: {fill: "#8ecafb 1"},
      selected: {fill: "#8ecafb 1"}
    },
    {
      x: 'B',
      value: 100,
      name: 'INGREDIENTS \n Key elements available',
      tooltipTitle: 'INGREDIENTS \n Key elements available',
      normal: {fill: "#ffeaa6 0.7"},
      hovered: {fill: "#ffeaa6 1"},
      selected: {fill: "#ffeaa6 1"}
    },
    {
      x: 'C',
      value: 100,
      name: 'COMPLEXITY \n Manageable level',
      tooltipTitle: 'COMPLEXITY \n Manageable level',
      normal: {fill: "#ee957f 0.7"},
      hovered: {fill: "#ee957f 1"},
      selected: {fill: "#ee957f 1"}
    },
    {
      x: ['A', 'C'],
      value: 20,
      name: 'Add to \n wishlist',
      tooltipTitle: 'Add to wishlist',
      tooltipDesc: 'Add the ingredients in the next shopping list',
      normal: {fill: "#a98caf 0.6"},
      hovered: {fill: "#a98caf 1"},
      selected: {fill: "#a98caf 1"},
      hatchFill: {
        type:"weave",
        color: "#8b6b92"
      }
    },
    {
      x: ['A', 'B'],
      value: 20,
      name: 'Possibility \n of disaster',
      tooltipTitle: 'Possibility of disaster',
      tooltipDesc: 'Keep a backup ready',
      normal: {fill: "#9fdebe 0.8"},
      hovered: {fill: "#9fdebe 1"},
      selected: {fill: "#9fdebe 1"},
      hatchFill: {
        type:"weave",
        color: "#83c3a3"
      }    
    },
    {
      x: ['B', 'C'],
      value: 20,
      name: 'Try on a \n holiday',
      tooltipTitle: 'Try on a holiday',
      tooltipDesc: 'When there is no other work pending',
      normal: {fill: "#f5b57c 0.8"},
      hovered: {fill: "#f5b57c 1"},
      selected: {fill: "#f5b57c 1"},
      hatchFill: {
        type:"weave",
        color: "#d09259"
      }
    },
    {
      x: ['A', 'B', 'C'],
      value: 30,
      name: 'The Perfect \n Recipe',
      tooltipTitle: 'The Perfect Recipe',
      tooltipDesc: 'Easy to follow and fast to cook with whatever is in the kitchen',
      label: {enabled:true, fontStyle: 'normal'},
      normal: {fill: "#8392ab 0.9"},
      hovered: {fill: "#8392ab 1"},
      selected: {fill: "#8392ab 1"},
      hatchFill: {
        type:"percent40",
        color: "#5f6b7d"
      }
    }
  ];

  // create venn diagram
  var chart = anychart.venn(data);

  // set chart title
  chart
    .title()
    .enabled(true)
    .fontFamily('Roboto, sans-serif')
    .fontSize(24)
    .padding({ bottom: 30 })
    .text('The Perfect Recipe to try while working from home');

  // set chart stroke
  chart.stroke('1 #fff');

  // set labels settings
  chart
    .labels()
    .fontSize(16)
    .fontColor('#5e6469')
    .hAlign("center")
    .vAlign("center")
    .fontFamily('Roboto, sans-serif')
    .fontWeight('500')
    .format('{%Name}');

  // set intersections labels settings
  chart
    .intersections()
    .labels()
    .fontStyle('italic')
    .fontColor('#fff')
    .format('{%Name}');

  // disable legend
  chart.legend(false);

  // set tooltip settings
  chart
    .tooltip()
    .titleFormat('{%tooltipTitle}')
    .format("{%tooltipDesc}")
    .background().fill("#000 0.5");

  // set container id for the chart
  chart.container('container');

  // initiate chart drawing
  chart.draw();
});

</script>

</body>
</html>
Please view this customized Venn diagram and the complete JS/CSS/HTML code on the Playground or CodePen.

in conclusion

This tutorial will show you how to quickly draw a Venn diagram and make it more attractive with various enhancements. You can experiment with colors, patterns and other possible custom alternatives. To learn more about Venn diagrams as a chart type, please refer to its configuration file on Chartopedia.

Some practical knowledge of HTML and JavaScript is always helpful. However, as we have seen, using a robust JavaScript chart library with pre-built chart types and ready-made functions to create visualization files is so simple that even without any technical knowledge, you can easily make useful and beautiful interactive charts. In addition, the special thing about AnyChart is that it has a large number of documents and other resources to help you easily create and customize visualizations.

We at AnyChart are happy to thank Shachee Swadia, an experienced data designer, for creating this excellent tutorial.

To continue learning and practicing data visualization, check out other JavaScript charting tutorials and see the complete list of charts that can be built and the main features that can be used with AnyChart. Then, create stunning visualizations in a quick and easy way.

related product recommendation:

AnyGantt-the ideal tool for building complex and rich Gantt charts

AnyStock-Flash financial chart solution based on XML/JSON

AnyMap-interactive map

If you want to buy genuine AnyChart license, or for more product information, please click [Consult online customer service]
This article is reprinted from [Huidu Technology] evget welcomes any form of reprinting, but please be sure to indicate the source and not modify the original related links, respect Other people's work

Guess you like

Origin blog.51cto.com/14874181/2551550