WANT THE COMPLETE CODE FOR THIS PROJECT ? DOWNLOAD THE ZIP FILE
SECTION 1 | DYNAMIC BUTTONS
If you want to create a button that is dependent on user preferences or user input - effectively letting the user dictate the name of the button then the following methods can be used. Here we look at creating buttons with Dynamic names and getting the name of a button via the post method to use in Python.
To send the button values from Python the the html template first_name = ("Daisy") last_name = ("May") return render_template ("pageName.html", first_name = first_name, last_name = last_name)
To render the buttons in HTML with the variable content sent from Python and include them in a form ready for the values to be passed back to Python. The values received in the HTML are in {{ }} this is Jinja2 framework that will receive the variables passed by Python. Note that both buttons have the same name, this is important as it is this name that Python will use to determine the button press.
<form action = "/buttonClick" method = "POST"> <p><input type = "submit" name = "BUTTON" value = "{{first_name}}" ></p> <p><input type = "submit" name = "BUTTON" value = "{{last_name}}" ></p> </form>
Next receiving the post in Python to determine which of the two buttons were pressed. First you need to receive the post then by using request.form["BUTTON"] this will get the value of the button pressed, because both buttons have the name BUTTON this will work for whichever button was pressed. In the case the value will then be stored in a variable called whichButton
JavaScript is one of the pillars of web development, alongside HTML and CSS. It is the language that makes web pages interactive, handling anything from form submissions to complex animations. This project utilises JavaScript so it is important to have a basic understanding of JavaScript principles and methods. If you have not done any JavaScript then you might want to visit the LEARN JAVASCRIPT page. However here is a quick overview of some of the principles used in this project
JAVASCRIPT SYNTAX JavaScript syntax is the set of rules that define how JavaScript programs are constructed, such as:
Variables: These are containers for storing data values. In JavaScript, we declare variables using let, const, or var keywords.
Data Types: JavaScript has several data types including Number, String, Boolean, Object, Null, and Undefined.
Operators: These are symbols used to perform operations. For example, + for addition, - for subtraction, and == for comparison.
Control Structures: These are used to handle the flow of the program. Examples include if, else, switch, for, while, and do...while.
Functions: Functions are blocks of code designed to perform a particular task. They're defined with the function keyword.
JAVASCRIPT EVENTS Events are actions that can be detected by JavaScript. When such actions occur, they can trigger JavaScript functions. Examples include clicking a button (onclick), submitting a form (onsubmit), or pressing a key (onkeydown).
JAVASCRIPT DOM MANIPULATION The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document and can be manipulated with JavaScript. This allows us to change content, structure, and styles of a webpage dynamically.
AYSYNCRONOUS JAVASCRIPT This project uses methods in asynchronous programming in JavaScript, including:
Callbacks: Functions that are passed as arguments to other functions and are invoked after some operation has completed.
Promises: Objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
Async/Await: A syntactic feature of JavaScript that uses promises to deal with asynchronous operations in a more straightforward, readable manner.
SECTION 3 | UNDERSTANDING JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
JSON is often used when data is sent from a server to a web page. Because of its compact size and the fact that it's easy to convert to JavaScript objects, JSON is an ideal format for transferring data between client and server.
JSON SYNTAX JSON syntax is derived from JavaScript object syntax, but JSON data is in text format. JSON syntax rules include the following:
Data is in name/value pairs: {"name":"John"}
Data is separated by commas: {"name":"John", "age":30, "city":"New York"}
Curly braces hold objects: {"employees":["John", "Anna", "Peter"]}
Square brackets hold arrays: {"employees":["John", "Anna", "Peter"]}
JSON WITH JAVASCRIPT Because JSON is derived from JavaScript, you can use standard JavaScript functions to work with JSON data.
JSON.parse(): This method converts a JSON text into a JavaScript object.
JavaScript | JSON parse
JSON.stringify(): This method converts a JavaScript object into a JSON text, which can then be sent to a server.
JavaScript | JSON stringify
JASON AND FETCH API The Fetch API provides a JavaScript interface for accessing and manipulating HTTP requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
When fetching data from an API, the response will often be in JSON format. You can use the .json() method to parse the response as JSON.
JAVASCRIPT | FETCH
Understanding how to work with JSON is crucial when dealing with data in modern web applications, including when working with Chart.js. Up next, we will introduce Chart.js and how we can use it to create beautiful, interactive charts.
SECTION 4 | INTRODUCTION TO CHARTJS
Chart.js is a popular open-source JavaScript library for creating interactive charts on websites and applications. It supports a variety of chart types, including line, bar, pie, doughnut, and more, which you can fully customize to your liking.
WHAT IS CHARTJS Chart.js utilizes the HTML5 canvas element to draw charts. The library provides flexible options to plot data, customize appearance, and create responsive charts, meaning the charts resize based on the screen size.
HOW CHART JS WORKS Chart.js works by binding to an HTML5 canvas element and using it to draw 2D shapes representing your data. It offers a simple and intuitive API, allowing you to create charts by specifying a configuration object.
WHERE YOU CAN USE CHARTJS Chart.js can be used anywhere you need to display data in a visually appealing way. It's often used in:
Web dashboards Data analytics tools Reporting interfaces Educational websites
TYPES OF CHARTS SUPPORTED BY CHARTJS Chart.js supports eight chart types, each highly customizable:
Line Chart: Best for showing trends over time. Each point in the line corresponds to a data value.
Bar Chart: Useful for comparing quantities related to different categories.
Radar Chart: Displays multivariate data in the form of a two-dimensional graph.
Doughnut/Pie Chart: Represents data in circles, excellent for showing proportions of a whole.
Polar Area Chart: Similar to pie/doughnut charts but uses radial sectors to display data.
Bubble Chart: Similar to a scatter plot, but data points are replaced with bubbles. The size of the bubble can represent a third variable.
Scatter Chart: Plots two-dimensional graphics that can be enhanced by additional point characteristics.
Area Chart: Similar to line charts but the area under the line is filled with colour.
STEP 5 | SETTING UP CHARTJS
Now that we have a basic understanding of what Chart.js is and what it can do, it's time to set it up in our project. This involves downloading and including the Chart.js library in our HTML files, understanding the basic structure of a Chart.js script, and using the HTML5 Canvas element to draw charts.
DOWNLOADING AND INCLUDING CHARTJS The easiest way to start using Chart.js is to download it from the official website (https://www.chartjs.org/) or include it in your project via a Content Delivery Network (CDN).
You have two options for using Chart.js:
Download: You can download the Chart.js library from the official website and include it in your project files locally. This means that you'll have a copy of Chart.js in your project directory, and you'll reference this local file in your HTML. To download it go to the official website (https://www.chartjs.org/)
CDN: Alternatively, you can include Chart.js directly from a Content Delivery Network (CDN). This means that you're linking to the Chart.js library hosted on a CDN, and your project will load the library directly from there.
You should choose one of these options, not both. Either way will work fine, and the best choice depends on your specific needs. If you anticipate working offline often, downloading might be the best choice. If you want to save space and ensure you always have the most up-to-date version, using a CDN might be the better option.
To include Chart.js via CDN, you can add the following line to your HTML file and the following inside the <head> tag:
HTML | INCLUDE CHARTJS
CANVAS ELEMENT
Canvas Element: A <canvas> element in your HTML is where the chart will be drawn. This element should have an id that you can reference in your JavaScript.
In the body of your HTML file place the <canvas> where you want your chart to be drawn
HTML | CANVAS ELEMENT
The <canvas> element is used to draw graphics on a web page. Chart.js uses the Canvas API to draw charts on the <canvas> element.
The <canvas> element is only a container for graphics - you must use JavaScript to actually draw the graphics. It has several methods for drawing paths, boxes, circles, characters, and adding images.
The id attribute of the <canvas> element is used in your JavaScript to link the <canvas> to your Chart.js configuration. The getContext('2d') used in the next section returns the drawing context on the canvas.
The id in the canvas element will link to the JavaScript part of the code.
STEP 6 | JAVASCRIPT CHART STRUCTURE
The JavaScript can either be placed in the HTML or in an external file. In this example we will create an external file for the JavaScript and link to it in the HTML.
The structure of the JavaScript file can be broken down in to 6 parts:
GETELEMENT BY | document.getElementById('myChart') : This part of the line is using the built-in JavaScript function getElementById to select the HTML element with the id of 'myChart'. In this case, it's the <canvas> element where we want to draw our chart.
GETCONTENT | .getContext('2d') : This part of the line is using the getContext method on the selected <canvas> element to get a drawing context on the canvas. '2d' indicates that we want to draw in two dimensions. The drawing context is what we actually draw on.
NEW CHART | var myChart = new Chart(ctx, { : This line is creating a new instance of a Chart.js chart. The new Chart() constructor creates a new chart in the given drawing context (ctx), which we obtained in the previous line.
CHART TYPE | type: 'bar' : This line is setting the type of the chart we want to create. In this case, we're creating a bar chart. Chart.js supports several types of charts including 'line', 'pie', 'doughnut', 'radar', 'polarArea', and 'scatter'.
CHART DATA | data: {} : This line is where we specify the data for our chart. The data object should contain properties for labels (an array of labels for each piece of data) and datasets (an array of dataset objects that each represent a set of data in the chart).
CHART OPTIONS | options: {} : This line is where we can specify configuration options for the chart. Options include settings for scaling, tooltips, legend, animation, and more.
JAVASCRIPT | CHART STRUCTURE
STEP 7 | CREATE A CHART WITH SAMPLE DATA
Now you have learnt the principles of the code and methods involved in creating a chart with this method we are ready to try your first chart. Create a new file in you coding environment in the same file location as your HTML file, you need to save it as a .js file type, in this example we have called the JavaScript file chart.js. Copy the sample data from below to your JavaScript file.
JAVASCRIPT | SAMPLE DATA
Next you will need to link to this in your HTML file. Copy the HTML from below, if both files are saved in the same location and you have named and linked to the correct name of your files then you are ready to test your code.
HTML | LINK TO YOUR JS FILE
<
>
<html> <head> <title>Constructors Championship 2023</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <p>My webpage to check out using CHARTJS</p> <canvas id="myChart" width = "50%"></canvas> <script src="{{ url_for('static', filename='chart.js') }}"></script> </body> </html>
You should now have 2 files and when you view the HTML file your chart should look like the one below:
CHANGE THE CHART SIZE
To adjust the height and width of the chart, you'll need to modify the CSS of the <canvas> element where the chart is drawn. Here's an example of how you can adjust the height and width directly in the HTML:
However, it's generally better to use CSS classes for styling. You could define a CSS class like this: <style> .chart-container { width: 800px; height: 400px; } </style> And then apply it to your <canvas> element: <div class="chart-container"> <canvas id="myChart"></canvas> </div>
Note: If you're using the responsive: true option in your Chart.js configuration (which is generally a good idea for ensuring that your chart looks good on all devices and screen sizes), Chart.js will use the size of the parent element of the <canvas> to determine the size of the chart. This is why we're setting the size on a wrapping <div> rather than directly on the <canvas>.
STEP 8 | CUSTOMISING YOUR CHART
Once we have our basic bar chart in place, we can start to customize it to suit our needs. Chart.js offers a wide range of customization options to adjust the look and feel of the chart, provide additional information, and improve the user experience.
CHART OPTIONS Chart.js provides a set of global chart options, which are used as defaults across all chart types. You can override these options for each individual chart. The options object is passed as a parameter when creating a chart:
responsive: If set to true, the chart will resize itself based on the size of its container.
title: You can add a title to your chart by setting this option to an object that includes a display property (set to true to display the title) and a text property (the text of the title).
tooltips: Tooltips appear when the user hovers over a data point. You can customize their appearance and the information they display.
legend: Controls the appearance and placement of the legend.
scales: Allows you to customize the axes of your chart. This can include changing the type of scale (linear, logarithmic, etc.), the labels on the axes, and more.
The code below demonstrates these chart options, copy the code and check out the changes.
JAVASCRIPT | CHART OPTIONS
The above code produces the outcome that can be seen below
STEP 8 | ADD TO YOUR PYTHON FLASK PROJECT
Rendering of the chart to your webpage requires the program to do the following process
An Python index app route will run the HTML template
The HTML template will run the JavaScript file
The JavaScript file will fetch the data from the Python data app route
the JavaScript file will receive the data returned from the data app route via return jsonify(data)
The chart will be rendered to the page
To add this to your Python / Flask project you will need to use the following methods:
Create folder and files: Create the exact folder structure needed and create the JS, HTML and Python files
Creating the index app routes: In your Python file you will need to create the index app route to link to your HTML page
Rendering the HTML Template: The index.html file is served to the client (your web browser). This file contains the structure of the webpage, a reference to the Chart.js library (loaded from a CDN), and a reference to your custom JavaScript file (chart.js).
Running the Custom JavaScript: Once the HTML file is loaded in the browser, the chart.js script is fetched from the Flask server (served from the '/static/chart.js' route) and executed in the browser. The script starts by sending a fetch request to the '/data' route of the Flask server.
Fetching the Data: The fetch request to the '/data' route is handled by the get_data function in your Flask application. This function returns a JSON response containing the data for your chart.
Creating the Chart: Back in the browser, the fetch promise resolves with the JSON data from the server. This data is then used to create a new Chart.js chart in the canvas element with the id of 'myChart'. The chart is configured according to the options specified in the chart.js script.
Accessing the Home Route: When you navigate to http://localhost:5000/ in your web browser, a GET request is sent to the Flask server. The server routes this request to the home function (which is associated with the '/' route in your Flask application). This function renders and returns the index.html template.
CREATE THE FOLDER AND FILES The folder structure needs to be exactly as shown below, the files can have different file names but you will then need to change the links in the code, the files must have the correct file extensions.
Save the Python file as app.py in your main project directory (MY WEBSITE).
Create a folder named templates in your main project directory, and save the HTML file as index.html in this folder.
Create another folder named static in your main project directory, and save the JavaScript file as chart.js in this folder.
Copy the three blocks of code below and place the content in the correct files
HTML | index.html
<
>
<!DOCTYPE html> <html> <head> <title>Constructors Championship 2023</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <p>My webpage to check out using CHARTJS</p> <canvas id="myChart" width = "50%"></canvas> <script src="{{ url_for('static', filename='chart.js') }}"></script> </body> </html>
JAVASCRIPT | chart.js
PYTHON | app.py
WANT THE CODE FOR THIS PROJECT ? DOWNLOAD THE ZIP FILE
GETTING YOUR DATA FROM A DATABASE ?
If you are pulling your data from a database you can simply pass the values in the the chart data as a list. In the example below the data is returned from the database as tuples within a list
PYTHON | PULLING YOUR DATA FROM A DATABASE
ALSO IN THIS TOPIC
DATA VISUALISATION HOME GETTING STARTED | BAR CHARTS | YOU ARE HERE PIE CHARTS | COMING SOON LINE GRAPHS | COMING SOON