Book Image

matplotlib Plotting Cookbook

By : Alexandre Devert
Book Image

matplotlib Plotting Cookbook

By: Alexandre Devert

Overview of this book

Table of Contents (15 chapters)
matplotlib Plotting Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Adding lines


When you have a very specific need in mind, the figures offered by matplotlib might not be of much help to you. All the graphics made by matplotlib consist of basic primitives. When demonstrating how to change the color of a boxplot, we mention that most matplotlib plotting functions return collections of lines and shapes. Now, we are going to demonstrate how to directly use a fundamental primitive: lines.

How to do it...

The following script will show a simple but aesthetic pattern made of independent lines:

import matplotlib.pyplot as plt

N = 16
for i in range(N):
  plt.gca().add_line(plt.Line2D((0, i), (N - i, 0), color = '.75'))

plt.grid(True)
plt.axis('scaled')
plt.show()

The preceding code gives the following output:

How it works...

In this script, we plot 16 independent lines. The pyplot.Line2D() function creates a new Line2D object. The mandatory parameters are the endpoints of the line. The optional parameters are all the parameters we have seen before for line-based figures...