Reader small image

You're reading from  Python Data Visualization Cookbook

Product typeBook
Published inNov 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781782163367
Edition1st Edition
Languages
Right arrow
Author (1)
Igor Milovanovic
Igor Milovanovic
author image
Igor Milovanovic

Igor Milovanović is an experienced developer, with strong background in Linux system knowledge and software engineering education. He is skilled in building scalable data-driven distributed software rich systems. An evangelist for high-quality systems design, he has a strong interest in software architecture and development methodologies. Igor is always committed to advocating methodologies that promote high-quality software, such as test-driven development, one-step builds, and continuous integration. He also possesses solid knowledge of product development. With field experience and official training, he is capable of transferring knowledge and communication flow from business to developers and vice versa. Igor is most grateful to his girlfriend for letting him spend hours on work instead with her and being an avid listener to his endless book monologues. He thanks his brother for being the strongest supporter. He is also thankful to his parents for letting him develop in various ways to become a person he is today.
Read more about Igor Milovanovic

Right arrow

Chapter 4. More Plots and Customizations

In this chapter we will learn about:

  • Setting the transparency and size of axis labels

  • Adding a shadow to the chart line

  • Adding a data table to the figure

  • Using subplots

  • Customizing grids

  • Creating contour plots

  • Filling an under-plot area

  • Drawing polar plots

  • Visualizing the filesystem tree using a polar bar

Introduction


In this chapter we will explore more advanced properties of the matplolib library. We are going to introduce more options and will look at how to achieve certain visually pleasing results.

During this chapter we will seek the solutions to some non-trivial problems with representing data when simple charts are not enough. We will try to use more than one type of graph or create hybrid ones to cover some advanced data structures and the representation required.

Setting the transparency and size of axis labels


The Axes label describes what the data in the figure represents and is quite important in the viewer's understanding of the figure itself. By providing labels to the axes background, we help the viewer comprehend the information in an appropriate way.

Getting ready

Before we dive into the code, it is important to understand how matplotlib organizes our figures.

At the top level, there is a Figure instance containing all that we see and some more (that we don't see). The figure contains, among other things, instances of the Axes class as a field Figure.axes. The Axes instances contain almost everything we care about: all the lines, points, and ticks and labels. So, when we call plot(), we are adding a line (matplotlib.lines.Line2D) to the Axes.lines list. If we plot a histogram (hist()), we are adding rectangles to the list of Axes.patches ("patches" is the term inherited from MATLAB™, and represents the "patch of color" concept).

An instance of...

Adding a shadow to the chart line


To be able to distinguish one particular plot line in the figure or just to fit in the overall style of the output our figure is in, we sometimes need to add a shadow effect to the chart line (or histogram, for that matter). In this recipe we will be learning how to add a shadow effect to the plot's chart lines.

Getting ready

To add shadows to the lines or rectangles in our charts, we need to use the transformation framework built in matplotlib and located in matplotlib.transforms.

To understand how it all works, we need to explain what transformations are in matplotlib and how they work.

Transformations know how to convert the given coordinates from their coordinate system into display. They also know how to convert them from display coordinates into their own coordinate system.

The following table summarizes existing coordinate systems and what they represent:

Adding a data table to the figure


Although matplotlib is mainly a plotting library, it helps us with small errands when we are creating a chart, such as having a neat data table beside our beautiful chart. In this recipe we will be learning how to display a data table alongside the plots in the figure.

Getting ready

It is important to understand why we are adding a table to a chart. The main intention of plotting data visually is to explain the otherwise not understandable (or hardly understandable) data values. Now, we want to add that data back. It is not wise just to cram a big table with values underneath the chart.

But, carefully picked, maybe the summed or highlighted values from the whole, charted dataset can identify important parts of the chart or emphasize the important values for those places where the exact value (for example, yearly sales in USD) is important (or even required).

How to do it...

Here's the code to add a sample table to our figure:

import matplotlib.pylab as plt
import...

Using subplots


If you are reading this book from the start, you are probably familiar with the subplot class, a descendant of axes that lives on the regular grid of subplot instances. We are going to explain and demonstrate how to use subplots in advanced ways.

In this recipe we will be learning how to create custom subplot configurations on our plots.

Getting ready

The base class for subplots is matplotlib.axes.SubplotBase. These subplots are matplotlib.axes.Axes instances but provides helper methods for generating and manipulating a set of Axes within a figure.

There is a class matplotlib.figure.SubplotParams, which holds all the parameters for subplot. The dimensions are normalized to the width or height of the figure. As we already know, if we don't specify any custom values, they will be read from the rc parameters.

The scripting layer (matplotlib.pyplot) holds a few helper methods to manipulate subplots.

matplotlib.pyplot.subplots is used for the easy creation of common layouts of subplots...

Customizing grids


A grid is usually handy to have under lines and charts as it helps the human eye spot differences in pattern and compare plots visually in the figure. To be able to set up how visibly, how frequently, and in what style the grid is displayed—or whether it is displayed at all—we should use matplotlib.pyplot.grid.

In this recipe we will be learning how to turn the grid on and off, and how to change the major and minor ticks on a grid.

Getting ready

The most frequent grid customization is reachable in the matplotlib.pyplot.grid helper function.

To see the interactive effect of this, you should run the following under ipython –pylab. The basic call to plt.grid() will toggle grid visibility in the current interactive session started by the last IPython PyLab environment:

In [1]: plt.plot([1,2,3,3.5,4,4.3,3])
Out[1]: [<matplotlib.lines.Line2D at 0x3dcc810>]

Now we can toggle the grid on the same figure:

In [2]: plt.grid()

We turn the grid back on, as shown in the following plot...

Creating contour plots


A contour plot displays the isolines of matrix. Isolines are curves where a function of two variables has the same value.

In this recipe we will learn how to create contour plots.

Getting ready

Contours are represented as a contour plot of matrix Z, where Z is interpreted as height with respect to the X-Y plane. Z is of minimum size 2 and must contain at least two different values.

The problem with contour plots is that if they are coded without labeling the isolines, they render pretty useless as we cannot decode the high points from low points or find local minimas.

Here we need to label the contour also. The labeling of isolines can be done either by using labels (clabel()) or colormaps. If your output medium permits the usage of color, colormaps are preferred because viewers will be able to decode data more easily.

The other risk with contour plots is choosing the number of isolines to plot. If we choose too many, the plot becomes too dense to decode, and if we go with...

Filling an under-plot area


The basic way to draw a filled polygon in matplotlib is to use matplotlib.pyplot.fill. This function accepts similar arguments as matplotlib.pyplot.plot—multiple x and y pairs and other Line2D properties. This function returns the list of Patch instances that were added.

In this recipe we will learn how to shade certain areas of plot intersections.

Getting ready

matplotlib provides several functions to help us plot filled figures, apart from plotting functions that are inherently plotting closed filled polygons, such as histogram (), of course.

We already mentioned one—matplotlib.pyplot.fill—but there are the matplotlib.pyplot.fill_between() and matplotlib.pyploy.fill_betweenx() functions too. These functions fill the polygons between two curves. The main difference between fill_between() and fill_betweenx() is that the latter fills between the x axis values, whereas the former fills between the y axis values.

The function fill_between accepts argument x—an x axis...

Drawing polar plots


If the data is already represented using polar coordinates, we can as well display it using polar figures. Even if the data is not in polar coordinates, we should consider converting it to polar form and draw on polar plots.

To answer whether we want to do this, we need to understand what the data represents and what we are hoping to display to the end user. Imagining what the user will read and decode from our figures leads us usually to the best of visualizations.

Polar plots are commonly used to display information that is radial in nature. For example, in sun path diagrams—we see the sky in radial projection, and the radiation maps of antennas radiate differently at different angles. You can learn more about this at: http://www.astronwireless.com/topic-archives-antenna-radiation-patterns.asp.

In this recipe, we will learn how to change the coordinate system used in the plot and to use the polar coordinate system instead.

Getting ready

To display data in polar coordinates...

Visualizing the filesystem tree using a polar bar


We want to show in this recipe how to solve a "real-world" task—how to use matplotlib to visualize our directory occupancy.

In this recipe we will learn how to visualize a filesystem tree with relative sizes.

Getting ready

We all have big hard drives that sometimes contain stuff that we usually forget about. It would be nice to see what is inside such a directory, and what the biggest file inside is.

Although there are many more sophisticated and elaborate software products for this job, we want to demonstrate how this is achievable using Python and matplotlib.

How to do it...

Let's perform the following steps:

  1. Implement a few helper functions to deal with folder discovery and internal data structures.

  2. Implement the main function, draw(), that does the plotting.

  3. Implement the main program body that verifies the user input arguments:

    import os
    import sys
    
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import numpy as np
    
    def build_folders...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Python Data Visualization Cookbook
Published in: Nov 2013Publisher: PacktISBN-13: 9781782163367
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Igor Milovanovic

Igor Milovanović is an experienced developer, with strong background in Linux system knowledge and software engineering education. He is skilled in building scalable data-driven distributed software rich systems. An evangelist for high-quality systems design, he has a strong interest in software architecture and development methodologies. Igor is always committed to advocating methodologies that promote high-quality software, such as test-driven development, one-step builds, and continuous integration. He also possesses solid knowledge of product development. With field experience and official training, he is capable of transferring knowledge and communication flow from business to developers and vice versa. Igor is most grateful to his girlfriend for letting him spend hours on work instead with her and being an avid listener to his endless book monologues. He thanks his brother for being the strongest supporter. He is also thankful to his parents for letting him develop in various ways to become a person he is today.
Read more about Igor Milovanovic

Coordinate system

Transformation object

Description

Data

Axes.transData

Represents the user...