Data visualization of python applications - using API (below)

foreword

  In the last article, we mainly introduced some of the contents of API use, mainly including a preliminary introduction to Git and GitHub that we often use, and also introduced how to call request data through API and introduce pip to install third-party software requests, Finally, the processing of API responses is introduced. This article mainly introduces the implementation of the remaining related functions of the API. The first introduction is to use Pygal to visualize the warehouse.

First, use Pygal to visualize the warehouse

  Now that we've got some interesting data from the last article , we can now visualize the Python popularity on GitHub. We'll create an interactive bar chart: the height of the bar indicates how many stars the project has received. , clicking the bar will take us to the home page of the project on github, the specific implementation is as follows:

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code: ", r.status_code)
#将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# 探索有关仓库的信息
repo_dicts = response_dict['items']
names, stars = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    stars.append(repo_dict['stargazers_count'])
# 可视化
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Starred Python Project on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')

  We first imported pygaland the Pygal styles we want to apply to the chart. Next print the status of the API call response and the total number of repositories found, so you know if there is a problem with the API call. We no longer print back information about items. Because this will present this information through visualization.
  With the above code, we first create two empty lists to store the information contained in the chart. We need the name of each item, which is used to label each bar, and how many stars the item has received, which is used to determine the height of the bar. In the loop, we append the item's name and the number of stars earned to the end of these lists.
  Next we LightStyledefine a style using the class (alias LS) and set its base color to dark blue, we also pass arguments base_styleto use the LightColorizedStyleclass (alias CLS), then we Bar()create a simple bar using image and passed it my_style. We also pass two other style arguments: rotate the labels 45 degrees around the x-axis ( x_label_rotation=45 ), and hide the legend ( show_shadow=False ) because we are only plotting one data series in the chart. Finally, we assign a title to the chart and set the property x_labelsto a list names.
  Since we don't need to add labels to this data series, we set the label to an empty string when adding data. The specific results are as follows:

  The generated svggraph is as follows:

  It can be seen from the graph that the popularity of the first few projects is much higher than that of other Python projects, but these projects play a crucial role in the Python ecosystem. Next, we will make a certain transformation of this chart, which is obviously a bit ugly.

2. Improve Pygal charts

  Next, to improve the above style chart, we will customize many aspects. Therefore, first of all, we will fine-tune the structure of the code and create a configuration object. In it contains Bar()all customizations to be passed to, implemented as follows:

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code: ", r.status_code)
#将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# 探索有关仓库的信息
repo_dicts = response_dict['items']
names, stars = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    stars.append(repo_dict['stargazers_count'])
# 可视化
my_style = LS('#333366', base_style=LCS)
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000
chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')

  It is not difficult to find through the code implemented above. First, we create an Configinstance of the Pygal class and name it my_config. By modifying my_configthe properties, the appearance of the chart can be customized. In addition, we set two properties - x_label_rotationand , which were originally passed as keyword arguments when the instance was show_legendcreated . BarNext, we set the font size of the chart's title, sublabel, and main label. In this chart, the sublabels are the items on the x-axis and most of the numbers on the y-axis. The primary labels are ticks on the y-axis that are multiples of 5000; these labels should be larger to distinguish them from the secondary labels, in the implementation of this code we used to truncate_labelshorten long items to 15 characters; if we Now point the mouse to the truncated item name on the screen. The full project name will be displayed. Also, we will show_y_guidesset to False, to hide the horizontal lines in the chart. Finally, we set a custom width to allow the chart to more fully utilize the space available in the browser.
  When we create an Barinstance, we my_configpass all configuration settings as the first argument. We can my_configreset the style chart by making any number of styling and configuration changes as shown:

3. Add custom tooltips

  In Pygal, pointing the mouse at a bar will display the information it represents, which is often called a tooltip. In this case, what is currently displayed is how many stars the item has received. Next we create a custom tooltip. to also display the item's description.
  Next, let's look at a simple example that does the following: Visualize the first three items and assign custom labels to the bars corresponding to each item. What we need to pay attention to here is that we are add()passing a list of dictionaries instead of a list of values . The specific implementation is as follows:

import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)

chart.title = 'Python Projects'
chart.x_labels = ['httpie', 'django', 'flask']

plot_dicts = [
    {
    
    'value': 16101, 'label': 'Description of httpie.'},
    {
    
    'value': 15028, 'label': 'Description of django.'},
    {
    
    'value': 14798, 'label': 'Description of flask.'},
    ]

chart.add('', plot_dicts)
chart.render_to_file('bar_descriptions.svg')

  First, we define a list called plot_dictslist that contains three dictionaries for items httpie, django, and flask, each with two keys: valueand lable. Pygal valuedetermines the height of the bar based on the number associated with the key, and labelcreates a tooltip for the bar using the string associated with it. For example, the first dictionary we pass plot_dictswill create a bar for an item that has earned 16101 stars with a tooltip of Description of httpie.
  The method add()takes a string and a list. When we call it here , we pass in a list ( ) add()of dictionaries representing the bars . plot_dictsThe specific analysis chart generated is as follows:

  From the chart, we can know that in addition to the default prompt (the number of stars obtained), Pygal also displays the custom prompt we passed in.

4. Drawing according to the data

  To plot against the data, we will automatically generate plot_dictsthe information for the 30 items returned by the API call. The code that implements this kind of work is as follows:

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
repo_dicts = response_dict['items']
names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])

    plot_dict = {
    
    
        'value': repo_dict['stargazers_count'],
        'label': repo_dict['description'],
    }
    plot_dicts.append(plot_dict)
my_style = LS('#333366', base_style=LCS)
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000
chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')

  In the above code, we first created two empty lists namesand plot_dicts. To generate the labels on the x-axis, we still need lists names.
  Inside the loop, for each item, we create a dictionary plot_dict. In this dictionary, we use the key to valuestore the number of stars and the key to labelstore the item description. plot_dictNext, we append the dictionary to the plot_dictsend. Finally, we pass the list plot_dictsto add(), and the resulting list is as follows:

5. Add clickable links to diagrams

  Pygal also allows you to use each bar in the chart as a link to your website. To do this, just add a line of code, in the dictionary created for each item, add a xlinkkey-value pair with a key of , as follows:

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)

response_dict = r.json()
print("Total repositories:", response_dict['total_count'])

repo_dicts = response_dict['items']

names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])

    plot_dict = {
    
    
        'value': repo_dict['stargazers_count'],
        'label': repo_dict['description'],
        'xlink': repo_dict['html_url'],
    }
    plot_dicts.append(plot_dict)

my_style = LS('#333366', base_style=LCS)

my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000

chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names

chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')

  Pygal xlinkturns each bar into an active link based on the URL associated with the key. When you click any bar in the chart, a new tab will be opened in the browser, and the GitHub page of the corresponding project will be displayed in it

  . Analysis and visualization, it is interactive and contains a lot of rich information! Originally, I wanted to expand and introduce a classic Hacker News APIrelated information analysis and visualization. Unfortunately, this website cannot be accessed now, so it is impossible to obtain data. I will introduce it to you when I have time!

Summarize

  In the last article, we mainly introduced some of the contents of API use, mainly including a preliminary introduction to Git and GitHub that we often use, and also introduced how to call request data through API and introduce pip to install third-party software requests, Finally, the processing of API responses is introduced. This article mainly introduces the implementation of the remaining related functions of the API. It mainly includes using Pygal to visualize warehouses, improving Pygal charts, adding custom tooltips, drawing based on data, and finally introducing adding clickable links to charts. Python is a practical language, it is the simplest of many programming languages, and it is also the best to get started. When you have learned the language, it is relatively simple to learn java, go and C. Of course, Python is also a popular language, which is very helpful for the realization of artificial intelligence. Therefore, it is worth your time to learn. Life is endless and struggle is endless. We work hard every day, study hard, and constantly improve our ability. I believe that we will learn something. come on! ! !

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324113401&siteId=291194637