Visualizing Repositories using Pygal
Pygal allows us to create a range of graphs and charts. In this article, you will learn how to construct a visualization that shows the comparative Pythons prominent works on GitHub. <!--more-->
Introduction
We'll create an interactive bar chart, where the height of each bar will represent the sum of stars earned by the project. By clicking a bar, you'll be sent to the project's GitHub page.
Prerequisites
To follow along the reader will need the following:
- Some knowledge of Python.
- Knowledge on Web APIs.
- Have Pip installed.
Installing Pygal
To install Pygal, run the command below:
pip install pygal
You can visit Pygal's official site for more information on the installation of Pygal.
The Pygal gallery
The Pygal gallery is a collection of charts that Pygal can generate.
To grasp more of the chart types that can be generated by Pygal, read over to the documentation tab on the chart type page.
Additionally, you can examine how the visualizations are created by exploring the source code for each.
Visualizing repositories
Since we'll want to incorporate more than one repository in our visualization. Let's design a loop that displays particular data about each of the repositories obtained by the API query, so we can incorporate them all in the visualization.
To achieve this, run the code below:
import requests
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' # Initiate an API request.
request = requests.get(url)
print("Status code:", request.status_code)
respons_dict = request.json() # In a variable, save the API response.
print("Total repos:", respons_dict['total_count'])
# Examine the repository's details.
repos_dicts = respons_dict['items']
print("Repos found:", len(repos_dicts))
print("\nSelected info about each repository:")
for repos_dict in repos_dicts: #go through all the dictionaries in repos_dicts.
print('name-:', repos_dict['name']) #write the name of the project
print('owner-:', repos_dict['owner']['login']) #show the owner of the project
print('stars-:', repos_dict['stargazers_count'])#print the number of stars the project has
print('repo-:', repos_dict['html_url']) # print the link to the project's repository
print('Description-:', repos_dict['description']) # print the description of the project
We print the owner of each project, its name, the number of stars it has, the project's description, and its GitHub URL inside the loop. Click here to see the output of the code above.
Let's construct a visual representation of the current popularity of Python works on GitHub since we have some relevant data. We will create a bar chart. It will show the tally of stars the project has earned will be represented by the height of each bar.
To get this done, you can run the code below:
import requests
import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
# Start an API request.
url = 'https://api.github.com/search/repositories?q=language:python&sort=star'
request = requests.get(url)
print("Status code:", request.status_code)
# In a variable, save the API response.
response_dictionary = request.json()
print("Total-repos:", response_dictionary['total_count'])
# Investigate the repository's contents.
repos_dicts = response_dictionary['items']
names, stars = [], []
for repos_dict in repos_dicts:
names.append(repos_dict['name'])
stars.append(repos_dict['stargazers_count'])
# Construct a visual picture
our_style = LSe('#333366', base_style=LCSe)
chart = pygal.Bar(style=our_style, x_label_rotation=45, show_legend=False)
chart.title = 'Python Works with the Most Stars on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('py_repos.svg')
To begin, we import pygal
as well as the Pygal styles
that we'll require for the chart. We'll keep printing the status of the API request return and the total amount of repositories detected to see if the API call was successful.
We need to generate two blank lists to house the data that will be used in the chart. We’ll use the name, and the number of stars of each project to label and determine the height of the bars respectively. The name of each work, as well as the amount of stars it has, are added to these lists inside the loop.
Next, we create a style based on a blue colored tint using the LightenStyle
class (alias LSe)
. In order to use the LightColorizedStyle class
(alias LCSe
), we additionally give the base style parameter. After that, we create a simple chart with Bar() and provide it our_style.
We further give two extra style arguments: we rotate the labels 45 degrees along the x-axis (x label rotation=45
) and conceal the legend since we're just showing one series on the graph (show legend=False
). The x labels
property is assigned to the list names, and the graph is given a title.
We give an empty string for the label once we load the data since we don't require this data series to be tagged.
Below we can see the graph that resulted:
Refining Pygal charts
Let's fine-tune the look of our graph. Let start by reorganizing the code somewhat by establishing a configuration object that includes all of our adjustments to pass to Bar()
:
import requests
import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
# Start an API request.
url = 'https://api.github.com/search/repositories?q=language:python&sort=star'
request = requests.get(url)
print("Status code:", request.status_code)
# In a variable, save the API response.
response_dictionary =request.json()
print("Total-repos:", response_dictionary['total_count'])
# Investigate the repository's contents.
repos_dicts = response_dictionary['items']
names, stars = [], []
for repos_dict in repos_dicts:
names.append(repos_dict['name'])
stars.append(repos_dict['stargazers_count'])
# Construct a visual picture
our_style = LSe('#333366', base_style=LCSe)
myconfig = pygal.Config() # make an instance of Pygal’s Config class
myconfig.x_label_rotation = 45 # set the attribute x_label_rotation to 45
myconfig.show_legend = False #set the attribute show_legend to false
myconfig.title_font_size = 23 #choose the text size for the heading of the chart
myconfig.label_font_size = 13 # choose the text size for the minor label (The minor labels are the project names along the x-axis)
myconfig.major_label_font_size = 17 #set the text size for the major label(The major labels are just the labels on the y-axis)
myconfig.truncate_label = 15 #To reduce the length of long project names to 15 characters, employ truncate label.
myconfig.show_y_guides = False #set show_y_guides to False hide the horizontal lines on the graph
myconfig.width = 1000 #Choose a custom width for the graph so that it takes up maximum browser area
chart = pygal.Bar(myconfig, style=our_style) #make an instance of Bar, and pass myconfig and style as arguments, respectively
chart.title = 'Python Projects with the Most Stars on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('py_repos.svg')
The restyled chart is shown below:
Customizing tooltips
Floating a mouse above a single bar displays data it represents. This is known as a tooltip, and it usually displays the tally of stars that a project possesses. Let's make a custom tooltip to display the descriptions of each project.
Let's have a look at an example that uses the first three projects plotted with custom labels for each bar. Rather than passing a list of values to add()
, we'll pass a list of dictionaries with the code below:
import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
our_style = LSe('#333366', base_style=LCSe)
chart = pygal.Bar(style=our_style, x_label_rotation=45, show_legend=False)
chart.title = 'Projects in Python '
chart.x_labels = ['public-apis', 'system-design-primer', 'Python']
plot_dictoinaries = [
{'value': 144904, 'label': 'Description of public-apis.'},
{'value': 139818, 'label': 'Description of system-design-primer.'},
{'value': 113616, 'label': 'Description of Python.'},
]
chart.add('', plot_dictoinaries)
chart.render_to_file('bar_desc.svg')
The list plot_dictionaries
is comprised of three dictionaries for public_apis
work, system_design_primer
work, and lastly for python
work. There are two keys in every dictionary: value
and label
.
Pygal calculates the height of each bar using the number linked with value
, and it creates the tooltip for each bar using the string connected with label
.
The first dictionary, for instance, will generate a bar indicating a project with 144904
stars, with the tooltip "Description of public-apis."
The add()
function requires a string and a list. We pass the list of dictionaries containing the bars (plot dictionaries) to add()
. Pygal has a default tooltip that contains the number of stars, besides the customized tooltip we gave it.
One of the tooltips is shown below:
Including clickable links in our charts
Each bar in the chart can also be used as a redirect to a webpage, thanks to Pygal. We simply add one line of code to our code to enable this feature, utilizing the dictionary we've built up for each project.
We create a new key-value
pair for each project’s plot_dictionary
using the key xlink
:
import requests
import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
# Initiate an API request
url = 'https://api.github.com/search/repositories?q=language:python&sort=star'
request = requests.get(url)
print("Status-code:", request.status_code)
# In a variable, save the API response.
response_dictionary = request.json()
print("Total repos:", response_dictionary['total_count'])
# Investigate the repository's contents.
repository_dicts = response_dictionary['items']
names, plot_dictionaries = [], []
for repository_dict in repository_dicts:
names.append(repository_dict['name'])
plot_dictionary = {
'value': repository_dict['stargazers_count'],
'label': repository_dict['description'],
'xlink': repository_dict['html_url'],
}
plot_dictionaries.append( plot_dictionary)
# Construct a visual picture
our_style = LSe('#333366', base_style=LCSe)
chart = pygal.Bar(style=our_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Starred Python Works on GitHub'
chart.x_labels = names
chart.add('', plot_dictionaries)
chart.render_to_file('py_rs.svg')
Here is the output of the above code:
Pygal converts each bar into an active link by using the URL connected with 'xlink.'
Any of the bars in the chart can be clicked to view the GitHub site for that project in a separate tab in your browser.
Conclusion
In this tutorial, we have seen how to:
- Install Pygal.
- Visualize repositories.
- Refining Pygal charts.
- Add Custom Tooltips.
- Add Clickable Links to our graphs.
Further reading
You can learn more about other concepts by visiting this page..
Happy coding!
Peer Review Contributions by: Elly Omondi