Javascript drawing graphs. How to Create an Interactive Graph Using CSS3 and jQuery

Graphs are an excellent visual aid when presenting data. Without them, it is impossible to create a high-quality admin panel. They are not that easy to install. However, there is new library, which makes this task easier is xCharts. Today we're going to use this program along with Twitter Bootstrap's Date Range palette to create a beautiful AJAX graph for your web application that pulls data from a MySQL table.

HTML

The demo structure of this language is quite simple - we have to add elements on the page to start plotting and to select information. Since we're enabling loading on the page anyway, we can use page styles and icons to give this structure a nice look.

index.php

Pretty Charts with jQuery and AJAX | Tutorialzine Demo

A lot of external resources are used here. In the main section we have the cascading stylesheet files for xCharts, the number sorter, upload (integrated from CloudFlare's super fast CDN), and our style.css file.

Before closing the table shortcut, we have the JQuery library, d3.js (required by the xсharts program), xcharts, a library with user-friendly interface sugar.js (which requires a "date range" plugin), a "date range" plugin, and a script.js file. Next you will see how it all works together.

MySQL

As I mentioned in the introduction, the script we are writing will fetch data from a MySQL table and display it in a chart. You can find the SQL code that will create the table in schema.sql in compressed file, available for download using top buttons. The table will look like this:

It only has three columns. The date column is assigned a unique index, which means there cannot be duplicate entries on the same day. The “sales records” column records the number of sales during the day. Your database will certainly be different, but as long as you get the correct answer into the format for structuring the data into a simple text format used to exchange JSON information from a PHP script, there will be no problems (more on this in the next section).

Note: Don't forget to enter your details MySQL connections in setup.php. Then you will have to create new base MySQL data and import schema.sql from the PHPMyAdmin system or from the management system of your choice.

PHP

In our PHP script we will select records from the table that correspond to the transmitted starting and ending information, collect all the data in an array, and display them in text format data exchange (JSON):

ajax.php

Header("Content-Type: application/json"); // setting up the library require_once("setup.php"); if (isset($_GET["start"]) AND isset($_GET["end"])) ( $start = $_GET["start"]; $end = $_GET["end"]; $data = array(); // select results $results = ORM::for_table("chart_sales") ->where_gte("date", $start) ->where_lte("date", $end) ->order_by_desc("date") ->find_array(); // create a new array with data foreach ($results as $key => $value) ( ​​$data[$key]["label"] = $value["date"]; $data[$ key]["value"] = $value["sales_order"]; echo json_encode($data);

Here I'm using my favorite library - Idiorm. I've used it in the past for website consultations (and many personal projects). This is only one file (located in the library/folder) and makes working with databases very easy. All I'm doing is fetching all results from the database that have a temporal value between the start and end timestamps consistent with the request for information.

The resulting JSON response looks something like this:

[( "label": "2013-01-07", "value": "4" ), ( "label": "2013-01-06", "value": "65" ), ( "label": "2013-01-05", "value": "96")]

The label properties contain the MySQL number values ​​in the corresponding row, and the columns contain the number of sales for that day. It just depends JavaScript code to properly process this data and transform it into a format suitable for sharing with xCharts plugin.

JavaScript

All JS code is in assets/js/script.js. The code is a bit long, and to make it easier to follow, I will present it to you in parts.

First we will set a few variables and initialize the date range picker plugin. Note that the dat range I used is a branch from original plugin. I decided to work with this version because the original depends on date.js, a legacy data library that conflicts with xCharts. Instead, sugar.js is used - an excellent useful library with reliable and up-to-date information.

assets/js/script. js

$(function() ( // set standard dates using shugar functions var startDate = Date.create().addDays(-6), // 6 days ago endDate = Date.create(); // today var range = $ ("#range"); // display dates in order of entry range.val(startDate.format("(MM)/(dd)/(yyyy)") + " - " + endDate.format("(MM)/ (dd)/(yyyy)")); // load the chart ajaxLoadChart(startDate,endDate); range.daterangepicker(( startDate: startDate, endDate: endDate, ranges: ( "Today": ["today", "today" ], "Yesterday": ["yesterday", "yesterday"], "Last 7 Days": , "Last 30 Days": // You can add more entries here ) ),function(start, end)( ajaxLoadChart(start, end); ));

As you can see, we have successfully used sugar.js' information and methods to determine the initial and end point range. I entered the results of the last 7 days into the script, and updated the range entry field.

Now let's create a graph:

// hint when pointing at the chart var tt = $("").appendTo("body"), topOffset = -32; var data = ( "xScale" : "time", "yScale" : "linear", "main" : [( className: ".stats", "data" : )] ); var opts = ( paddingLeft: 50, paddingTop: 20, paddingRight: 10, axisPaddingLeft: 25, tickHintX: 9, // How many ticks to show horizontally dataFormatX: function(x) ( // the timestamp that came with // ajax is converted here .php into the corresponding JavaScript Date object return Date.create(x); ), tickFormatX: function(x) ( // set the label format for the x axis return x.format("(MM)/(dd)"); ), "mouseover": function (d, i) ( var pos = $(this).offset(); tt.text(d.x.format("(Month) (ord)") + ": " + d.y).css(( top: topOffset + pos.top, left: pos.left )).show(); ), "mouseout": function (x) ( tt.hide(); ) ); // Create a new xChart instance, passing the chart type //, a set of dates and additional functions var chart = new xChart("line-dotted", data, "#chart" , opts);

First I define an xCharts configuration object with its properties and inverse functions. In the dataFormatX property I transform the yyyy-mm-dd strings returned from the AJAX request into the proper ones JavaScript objects Date so that the plugin can display them correctly and do its calculations.

I also use an information handler for the mouseover/mouseout plugin, and use it to show a tooltip (the plugin doesn't come with one of the modules).

Finally, here's a JavaScript function to load data via AJAX:

// function for loading data via AJAX and displaying it on the chart function ajaxLoadChart(startDate,endDate) ( // if there is no data, the chart will be empty if(!startDate || !endDate)( chart.setData(( "xScale" : "time ", "yScale" : "linear", "main" : [( className: ".stats", data: )] )); return; ) // otherwise, create an ajax request $.getJSON("ajax.php ", ( start: startDate.format("(yyyy)-(MM)-(dd)"), end: endDate.format("(yyyy)-(MM)-(dd)") ), function(data) ( var set = ; $.each(data, function() ( set.push(( x: this.label, y: parseInt(this.value, 10) )); )); chart.setData(( "xScale" : "time", "yScale" : "linear", "main" : [( className: ".stats", data: set )] ));

xCharts provides a setData method so you can easily move or replace the displayed data. The className attribute is important because it is what the plugin uses to define your graph. If you ignore it, all sorts of weird bugs can happen (trust me, I know).

This completes our beautiful diagram!

End!

You can use this example to improve your management areas and visualize statistical data in a beautiful interface.

Good afternoon, my dear reader, today I want to offer you a wonderful selection of plugins and examples for creating various types of charts and graphs. I think everyone will find something interesting for themselves.

1. jqPlot - Universal and extensible JQuery Plugin for plotting

jqPlot - JQuery Plugin for plotting graphs in Javascript.
jqPlot produces beautiful lines, bars and pie charts with many features:
Numerous chart styles.
Axis data with custom formatting.
Up to 9 Y axes.
Rotate axis text.
Automatic trend line calculation.
Tooltips.
Ease of use.

2. Dygraphs visualization library

Dygraphs is an open source library source code, which produces interactive, scalable time series graphs. It is designed to display dense data sets and allow users to explore and interpret them.

Peculiarities:
Display time series without using external servers or Flash animation
Works in Internet Explorer(via excanvas)
Small size (69kb)
Displays values ​​on mouseover
Interactive zoom
Adjustable averaging period
Compatible with Google Visualization API
http://dygraphs.com/

3. Highcharts - Interactive JavaScript charts for your website

Highcharts is a charting library written in pure JavaScript, offering interactive charts for your website or web application. Highcharts currently supports line, spline, area, areaspline, column, bar, pie, scatter, angle gauges, arearange, areasplinerange, columnrange and polar chart types.

4. JQuery with mouse wheel scroll effect

Does not use PNG or JPG sprites.
Handles touch, mouse wheel, and keyboard events.
http://anthonyterrien.com/knob/

5. Stylish indicators using CSS3

Stylish, animated indicators using CSS3.
http://www.red-team-design.com

6. Highcharts with JQuery

Highcharts is a JQuery and Mootools compatible charting library. It is compatible with all standard web browsers and uses JSON data to build the graph. Supports several graph types: line, spline, area, areaspline, column, bar, pie and scatter plot.
Highcharts.com

7. Animated graph in HTML5 and JQuery

A beautiful, interactive pie chart using latest technologies HTML5. Doesn't use Flash.

8. Experimental graph in CSS3

This method is an example of building experimental graphics in CSS3, without JavaScript or images. The use of CSS3 selectors is truly impressive: transformations, gradients and transitions in use. Unfortunately not supported in IE.

9. Another diagram in JQuery and HTML5

Visualize plugin analyzes key content elements in a structured HTML table, and uses HTML5 to turn them into a chart or graph. For example, in a data table, rows can serve as a chart of bars, lines, or wedges. Visualize also automatically checks the maximum and minimum values ​​in the table and uses them to calculate the x-axis values ​​for the line and histogram. Finally, the plugin includes two different CSS styling- light and dark which can be used as is, or can serve as a starting point for customizing charts and graphs.

In this article we will create interactive chart using CSS3 and jQuery. We will use a popular jQuery library - Flot. Flot is a pure javascript library for drawing graphs used in jQuery. This plugin is simple yet powerful enough to create beautiful and interactive graphics. For more information about the library, please refer to the official flot documentation.


HTML markup

First, let's create the HTML markup for the graph. Let's create a block with the graph-wrapper class. Inside this block we will place two blocks. The first block, with the graph-info class, will contain a legend for the graphs and buttons for switching between the appearance of the graphs. The second block contains graphs (line and bar).

HTML Visitors Returning Visitors jQuery and the Flot library

Let's connect javascript. First, let's connect the jquery library (for example, from google). You can use the same link or upload the jQuery library file to your server. Then download the Flot files and include jquery.flot.min.js.

HTML $(document).ready(function () ( // Graph scripts here )); Data for the graph

The data for the graph is an array of the form: . We will also set custom options for each data type.

jQuery var graphData = [( // Visits data: [ , , , , , , , , , ], color: "#71c73e" ), ( // Returning Visits data: [ , , , , , , , , ], color: "#77b7c5", points: ( radius: 4, fillColor: "#77b7c5" ) ) ]; Loading charts

Now we will load two graphs, one line, the other bar. Both have several custom options (color, shadow, etc.). Also both use data from the graphData variable.

jQuery // Linear $.plot($("#graph-lines"), graphData, ( series: ( points: ( show: true, radius: 5 ), lines: ( show: true ), shadowSize: 0 ), grid : ( color: "#646464", borderColor: "transparent", borderWidth: 20, hoverable: true ), xaxis: ( tickColor: "transparent", tickDecimals: 2 ), yaxis: ( tickSize: 1000 ) ); // Bars $.plot($("#graph-bars"), graphData, ( series: ( bars: ( show: true, barWidth: .9, align: "center" ), shadowSize: 0 ), grid: ( color: "#646464", borderColor: "transparent", borderWidth: 20, hoverable: true), xaxis: ( tickColor: "transparent", tickDecimals: 2), yaxis: ( tickSize: 1000 )); Styles for the wrapper block and its children

First, let's reset the default styles for all elements in the parent block of the graphs ( good practice start website layout with style reset connections).

CSS /* Resets */ .graph-container, .graph-container div, .graph-container a, .graph-container span ( margin: 0; padding: 0; ) Add a gradient and rounded corners wrapper, buttons and tooltips. CSS /* Gradinet and Rounded Corners */ .graph-container, #tooltip, .graph-info a ( background: #ffffff; background: -moz-linear-gradient(top, #ffffff 0%, #f9f9f9 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#f9f9f9)); background: -webkit-linear-gradient(top, #ffffff 0%,#f9f9f9 100%); background: -o-linear-gradient(top, #ffffff 0%,#f9f9f9 100%); background: -ms-linear-gradient(top, #ffffff 0%,#f9f9f9 100%); background: linear-gradient(to bottom, #ffffff 0%,#f9f9f9 100%); -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; )

Finally, in the next step we will add positioning to the parent block, as well as assign width, height and padding to it. Feel free to experiment with these values ​​depending on your design preferences and chart sizes.

CSS /* Graph Container */ .graph-container ( position: relative; width: 550px; height: 300px; padding: 20px; -webkit-box-shadow: 0px 1px 2px rgba(0,0,0,.1); -moz-box-shadow: 0px 1px 2px rgba(0,0,0,.1); box-shadow: 0px 1px 2px rgba(0,0,0,.1); .graph-container > div ( position : absolute; width: inherit; top: 10px; .graph-info ( width: 590px; margin-bottom: 10px; )


Legend and buttons

Let's start by adding some basic styles for the links. For the graph legends, let's create a small circle with the same color as the graphs themselves (line/bar). To create a circle we will use the pseudo-selector:before . This selector will allow us to insert content before the content of the element it is being appended to.

CSS .graph-info a ( position: relative; display: inline-block; float: left; height: 20px; padding: 7px 10px 5px 30px; margin-right: 10px; text-decoration: none; cursor: default; ) CSS /* Color Circles */ .graph-info a:before ( position: absolute; display: block; content: ""; width: 8px; height: 8px; top: 13px; left: 13px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; .graph-info.visitors ( border-bottom: 2px solid #71c73e; ) .graph-info.returning ( border-bottom: 2px solid #77b7c5 ; ) .graph-info .visitors:before ( background: #71c73e; ) .graph-info .returning:before ( background: #77b7c5; )

Next, we'll add styles to the two buttons that allow us to switch between a line graph and a bar graph.

Finally, let's prevent the blocks from collapsing.

CSS /* Clear Floats */ .graph-info:before, .graph-info:after, .graph-container:before, .graph-container:after ( content: ""; display: block; clear: both; ) Switch graphs

At this step, we will add a click event for the “bar” and “linear” buttons. When loading, we will hide the bar graph, then when we click on the “bar” button we will make the graph visible. To see a line graph, the user must click on the “line” button.

jQuery $("#graph-bars").hide(); $("#lines").on("click", function (e) ( $("#bars").removeClass("active"); $("#graph-bars").fadeOut(); $( this).addClass("active"); $("#graph-lines").fadeIn(); $("#bars").on("click", function (e) ( $("#lines").removeClass("active"); $("#graph-lines").fadeOut(); $( this).addClass("active"); $("#graph-bars").fadeIn().removeClass("hidden"); Text

Adding a font and styles for the text.

CSS #tooltip, .graph-info a ( font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: bold; font-size: 12px; line-height: 20px; color: #646464; ) .tickLabel ( font-weight: bold; font-size: 12px; color: #666; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; )

Let's hide the styles for the first and last value along the y axis:

CSS .yAxis .tickLabel:first-child, .yAxis .tickLabel:last-child ( display: none; ) Tooltip

Let's add a tooltip inside the body element. The tooltip will be a block with id equal to tooltip . The position for the tooltip will be calculated based on the position of the graph points. The tooltip will only be shown when you hover over the graph points.

jQuery function showTooltip(x, y, contents) ( $("" + contents + "").css(( top: y - 16, left: x + 20 )).appendTo("body").fadeIn(); ) var previousPoint = null; $("#graph-lines, #graph-bars").bind("plothover", function (event, pos, item) ( if (item) ( if (previousPoint != item.dataIndex) ( previousPoint = item.dataIndex ; $("#tooltip").remove(); var x = item.datapoint, y = item.datapoint; showTooltip(item.pageX, item.pageY, y + " visitors at " + x + ".00h") ; ) ) else ( $("#tooltip").remove(); previousPoint = null; ) ));

Then add a hint absolute positioning, padding, borders and set display to none .

CSS #tooltip ( position: absolute; display: none; padding: 5px 10px; border: 1px solid #e1e1e1; )


Conclusion

That's all. We're done using CSS3 and the flot plugin to customize the charts. Good luck.

  • Translation

It's almost impossible to imagine a dashboard without charts and graphs. They display complex statistics quickly and efficiently. Moreover, a good diagram also improves the overall design of your website.

In this article, I will show you some of the best JavaScript libraries for diagramming (and pivot tables). These libraries will help you in creating beautiful and customizable graphics for your future projects.

Although most libraries are free and redistributable, some of them have paid versions with additional functionality.

D3.js - data-centric documents Today, when we think about graphs, the first thing that comes to mind is D3.js. open source project, D3.js undoubtedly provides many useful features that most existing libraries lack. Features such as “ Enter and Exit”, powerful transitions, and syntax similar to jQuery or Prototype make it one of the best JavaScript libraries for creating graphs and charts. In D3.js they are generated using HTML, SVG and CSS.

Unlike many other JavaScript libraries, D3.js does not come with pre-built graphs right out of the box. However, you can take a look at the list of graphs created with D3.js to get a general idea.

D3.js does not work properly with older browsers such as IE8. But you can always use plugins like aight plugin for cross-browser compatibility.

D3.js has previously been widely used on websites such as NYTimes, Uber and Weather.com

Google Charts


Google Charts is a JavaScript library that I regularly use to create charts simply and easily. Provides many pre-built charts such as combined histograms, bar charts, calendar charts, pie charts, geo diagrams, etc.

Google charts also has a variety of configuration settings that can help you change the appearance of your chart. The graphics are generated using HTML5/SVG to ensure cross-browser compatibility and cross-platform portability to iPhone, iPad and Android. Also contains VML to support older IE versions.

Highcharts JS


Highcharts JS is another very popular charting library. It comes with a large number of animations of various types that can attract a lot of attention to your site. Like other libraries, HighchartsJS contains many pre-created charts: spline, shape, combination, column, histogram, pie, scatter, etc.

One of the most great benefits HighchartsJS applications – compatibility with older browsers such as Internet Explorer 6. Standard browsers use SVG to render graphs. In legacy IE, graphs are built via VML.

Although HighchartsJS is free for personal use, you need to purchase a license for commercial use.

Fusioncharts


Fusioncharts is one of the oldest JavaScript libraries, first released in 2002. Graphs are generated using HTML5/SVG and VML for better portability and compatibility.

Unlike many libraries, Fusioncharts provides the ability to parse both JSON data and XML. You can also export these graphs in 3 different formats: PNG, JPG and PDF.

Fusioncharts is highly compatible with older browsers such as IE6. And for this reason, it has become one of the most preferred libraries in many trade organizations.

You can use the watermarked version of Fusioncharts for free in both personal and commercial projects. However, you need to purchase a license to get rid of the watermark.

Flot


Flot is a JavaScript library for JQuery that allows you to create graphs/charts. One of the oldest and most popular diagram libraries.

Flot supports bar charts, scatter charts, bar charts, column charts, and any combination of these chart types. Also compatible with older browsers such as IE 6 and Firefox 2.

Flot is completely free, commercial support available upon special request to the developer. Here is a list of examples with charts created in Flot.

amCharts


amCharts is undoubtedly one of the best looking chart libraries out there. It is fully divided into 3 independent types: JavaScript Charts, Maps Charts (amMaps) and Stock charts.

AmMaps is my favorite of the three above. Provides features such as heat maps, drawing lines, adding text to the map, loading icons or photos to the top of your map, changing the scale, etc.
amCharts uses SVG to render charts which only works in modern browsers. Graphs may not display correctly in IE below version 9.

EJS Chart is provided free of charge and paid versions. Free version has a limitation that does not allow you to use more than 1 chart per page and more than two (numeric) sequences per chart. Check out pricing details.

uvCharts


uvCharts is an open source JavaScript library that claims to have over 100 configuration options. It has charts for 12 different standards right out of the box.

UvCharts is built on the D3.js library. This project promises to eliminate all the complex nuances of D3.js coding and provide easy implementation of graphs standard view. uvCharts is generated using SVG, HTML and CSS.

Conclusion Now the choice of the best diagram library for your future projects is up to you. Developers who need full control over graphs, they will definitely choose D3.js Almost all of the above libraries have good support on the Stackoverflow forums.

I hope you enjoyed this article. Have a good day.

You learned how to install and use Chart.js. You also learned some global options that let you change the font and tooltips for different graphs. In this tutorial, you know how to create line and column charts using Chart.js.

Creating Line Charts

Line charts are useful when you want to show the change in the value of a given variable relative to changes in some other variable. The other variable is usually temporary. For example, line charts can be used to show the speed of a vehicle over specific periods of time.

Chart.js allows you to create line charts by setting the type to line . Here's an example:

Var lineChart = new Chart(speedCanvas, ( type: "line", data: speedData, options: chartOptions ));

We will now provide the data as well as the configuration parameters that we need to build the line chart.

Var speedData = ( labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"], datasets: [( label: "Car Speed", data: , )] ); var chartOptions = ( legend: ( display: true, position: "top", labels: ( boxWidth: 80, fontColor: "black" ) ) );

In this part, we will focus on various options specifically designed for modifying line charts. All the parameters and data we have provided above create the following chart.

The color of the area under the curve is determined by the backgroundColor key. All line charts created using this method will be filled with this color. You can set the fill key to false if you just want to draw a line, without filling the day area with any color.

Another thing you may have noticed is that we use individual data pointers (points) to plot the chart. The library automatically interpolates the values ​​of all other points using built-in algorithms.

By default, points are plotted using custom weighted cubic interpolation. However, you can set the cubicInterpolationMode key to monotone for more accurate point plotting if the plot you are creating is defined by the equation y = f (x) . The elasticity of the Bezier curve is determined by the lineTension key. You can set its value to zero to draw straight lines. Note that this key is ignored if cubicInterpolationMode is already specified.

You can also set the border color and width using the borderColor and borderWidth keys. If you want to plot a chart using a dotted line instead of a solid line, you can use the borderDash key. It takes an array as values, the elements of which define the length and spacing of the strokes, respectively.

The appearance of plotted points can be controlled using the pointBorderColor, pointBackgroundColor, pointBorderWidth, pointRadius, and pointHoverRadius properties. There is also a pointHitRadius key, which determines the distance from which points on the graph will begin to interact with the mouse.

Var speedData = ( labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"], datasets: [( label: "Car Speed", data: , lineTension: 0, fill: false, borderColor: "orange", backgroundColor: "transparent", borderDash: , pointBorderColor: "orange", pointBackgroundColor: "rgba(255,150,0,0.5)", pointRadius: 5, pointHoverRadius: 10, pointHitRadius: 30, pointBorderWidth: 2, pointStyle: "rectRounded" )] );

The above speedData object displays the same data points as the previous graph, but with different values ​​set for all properties.

You can also plot several lines on one graph and set various parameters to draw each one like this:

Var dataFirst = ( label: "Car A - Speed ​​(mph)", data: , lineTension: 0.3, // Set More Options ); var dataSecond = ( label: "Car B - Speed ​​(mph)", data: , // Set More Options ); var speedData = ( labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"], datasets: ); var lineChart = new Chart(speedCanvas, ( type: "line", data: speedData ));

Creating Column Charts

Column charts (or histograms) are useful when you want to compare one measurement for different objects - for example, the number of cars sold by different companies, or the number of people of a certain age group in a city. You can create bar charts in Chart.js by setting the type key to bar . By default, this will create charts with vertical bars. If you want to create charts with horizontal bars, you must set the type to horizontalBar .

Var barChart = new Chart(densityCanvas, ( type: "bar", data: densityData, options: chartOptions ));

Let's create a histogram that displays the density of all the planets in our solar system. Density data was taken from the Planet Information List provided by NASA.

Var densityData = ( label: "Density of Planets (kg/m3)", data: ); var barChart = new Chart(densityCanvas, ( type: "bar", data: ( labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", " Neptune"], datasets: ) ));

The options above will create the following chart:

Same as in line charts, stripes are filled light gray. You can change the color of the bars using the backgroundColor key. Likewise, the color and width of the borders of different stripes can be set using the borderColor and borderWidth keys.

If you want the library to not draw borders for a particular side, you can specify the side as the value for the borderSkipped key. You can set the following values: top , left , bottom or right . You can also change the borders and background color of the various bars you see when you hover your mouse over them using hoverBorderColor and hoverBackgroundColor .

The size of the columns in the bar chart above was calculated automatically. However, you can control the width of individual columns using the barThickness and barPercentage properties. The barThickness key is used to set the thickness of the columns in pixels, and barPercentage is used to set the thickness as a percentage of the available group width.

Let's make the density (planet) plot more interesting by overriding the default values ​​for histograms using the following code.

Var densityData = ( label: "Density of Planets (kg/m3)", data: , backgroundColor: [ "rgba(0, 99, 132, 0.6)", "rgba(30, 99, 132, 0.6)", " rgba(60, 99, 132, 0.6)", "rgba(90, 99, 132, 0.6)", "rgba(120, 99, 132, 0.6)", "rgba(150, 99, 132, 0.6)" , "rgba(180, 99, 132, 0.6)", "rgba(210, 99, 132, 0.6)", "rgba(240, 99, 132, 0.6)" ], borderColor: [ "rgba(0, 99 , 132, 1)", "rgba(30, 99, 132, 1)", "rgba(60, 99, 132, 1)", "rgba(90, 99, 132, 1)", "rgba(120 , 99, 132, 1), "rgba(150, 99, 132, 1)", "rgba(180, 99, 132, 1)", "rgba(210, 99, 132, 1)", "rgba (240, 99, 132, 1)" ], borderWidth: 2, hoverBorderWidth: 0 ); var chartOptions = ( scales: ( yAxes: [( barPercentage: 0.5 )] ), elements: ( rectangle: ( borderSkipped: "left", ) ) ); var barChart = new Chart(densityCanvas, ( type: "horizontalBar", data: ( labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", " Neptune"], datasets: , ), options: chartOptions ));

The densityData object is used to set the borders and background color of the columns. There are two things to note in the above code. First, the values ​​of the barPercentage and borderSkipped properties were set inside the chartOptions object instead of the dataDensity object.

Second, this time the chart type is set to horizontalBar . Which also means that you will have to change the barThickness and barPercentage value for the Y axis instead of the X axis for these values ​​to have any effect on the columns.

The above options will create the following histogram.

You can also plot multiple data sets on the same chart by assigning a specific axis id to a specific data set. The xAxisID key is used to assign an id to any X-axis in your dataset. Likewise, the yAxisID key is used to assign an ID to any axis in your dataset. Both axes also have an id key, which you can use to assign unique identifiers to them.

If the last paragraph was a little confusing, the following example will help clear things up.

Var densityData = ( label: "Density of Planet (kg/m3)", data: , backgroundColor: "rgba(0, 99, 132, 0.6)", borderColor: "rgba(0, 99, 132, 1)", yAxisID: "y-axis-density" ); var gravityData = ( label: "Gravity of Planet (m/s2)", data: , backgroundColor: "rgba(99, 132, 0, 0.6)", borderColor: "rgba(99, 132, 0, 1)", yAxisID: "y-axis-gravity" ); var planetData = ( labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"], datasets: ); var chartOptions = ( scales: ( xAxes: [( barPercentage: 1, categoryPercentage: 0.6 )], yAxes: [( id: "y-axis-density" ), ( id: "y-axis-gravity" )] ) ) ; var barChart = new Chart(densityCanvas, ( type: "bar", data: planetData, options: chartOptions ));

Here we have created two Y axes with unique identifiers and they were assigned to separate datasets using the yAxisID key. The barPercentage and categoryPercentage keys are used to group the columns for individual planets. Set categoryPercentage to a lower value to increase the distance between columns of different planets. Likewise, setting barPercentage to more high value, we will reduce the distance between the columns of the same planet.

Lastly

In this tutorial, we covered all aspects of line and column charts in Chart.js. You should now be able to create basic charts, change their appearance, and display multiple data sets on a single chart without any problems. In the next part of the series, you will learn about radial and polar charts in Chart.js.

I hope you enjoyed this tutorial. If you have any questions, please post them in the comments.