Examples of Creating Charts and Plots using Pygal in Python
Now we will see some examples of creating interactive Charts and Plots using Pygal in Python.
Create a Pie Chart using Pygal in Python
In the below example, we will draw a pie chart using the Pygal library. First, we import the Pygal library, and then create an instance of a pie chart using pygal.Pie() method. Set the title of a pie chart. Add data to the pie chart using add() method by passing the label name and value as an argument in it. Finally, save the output to the SVG file.
Python3
# importing pygal import pygal # Creating Pie chart object pie_chart = pygal.Pie() # Set the title of pie chart pie_chart.title = '% of different section in SDE Interview' # Add data to pie chart pie_chart.add( 'Aptitude' , 10 ) pie_chart.add( 'OOPs' , 20 ) pie_chart.add( 'DSA' , 40 ) pie_chart.add( 'Project' , 30 ) # Render the bar chart to SVG file pie_chart.render_to_file( 'Pie_chart.svg' ) |
Output:
Create a Stacked Line Chart using Pygal in Python
In the below example, we will draw a stacked line chart using the Pygal library. First, we import the Pygal library and then create sample data of 6 months’ sales of various courses at GFG. Create an instance of a stacked line chart using pygal.StackedLine() method and set fill as true so that the area between two lines or a line and the x-axis is filled with color. Set the title of a pie chart and x-axis labels. Add data to the pie chart using add() method by passing the label name and value as an argument in it. Finally, save the output to the SVG file.
Python3
import pygal # Sample Sales data for different cources on GFG months = [ 'Apr' , 'May' , 'Jun' , 'Jul' , 'Aug' , 'Sept' ] DSA_Self_Paced = [ 12000 , 15000 , 18000 , 14000 , 16000 , 20000 ] Java_Backend = [ 8000 , 10000 , 12000 , 9000 , 11000 , 13000 ] CIP = [ 8800 , 14000 , 12500 , 8500 , 10900 , 12900 ] DSA_Offline = [ 5000 , 6000 , 7000 , 5500 , 6500 , 7500 ] Web_Dev_Offline = [ 4500 , 6100 , 5100 , 7500 , 3500 , 2500 ] # Create a stacked line chart line_chart = pygal.StackedLine(fill = True ) # Title and labels line_chart.title = 'Monthly Sales by Product Category' line_chart.x_labels = months # Add data to the chart line_chart.add( 'DSA Self Paced' , DSA_Self_Paced) line_chart.add( 'Java Backend' , Java_Backend) line_chart.add( 'Complete Interview Preparation' , CIP) line_chart.add( 'DSA Offline' , DSA_Offline) line_chart.add( 'Web Dev Offline' , Web_Dev_Offline) # Save the chart to a file line_chart.render_to_file( 'stacked_line_chart.svg' ) |
Output:
Pygal Introduction
Python has become one of the most popular programming languages for data science because of its vast collection of libraries. In data science, data visualization plays a crucial role that helps us to make it easier to identify trends, patterns, and outliers in large data sets. Pygal is best suited for Data visualizations. It is used to draw charts and plots such as bar plots, line charts, and box plots.
Contact Us