Matplotlib: plotting (translation), matplotlibplotting

Source: Internet
Author: User

Matplotlib: plotting (translation), matplotlibplotting

Thanks

Thank you very much for reviewing and correcting Bill Wing and Christoph Deil.

Author:Nicolas Rougier, Mike Müller, Ga ë l Varoquaux

Content of this chapter:

  • Introduction
  • Simple plotting
  • Graphics, subgraphs, axes, and scales
  • Other types of graphics: examples and exercises
  • Content not included in the tutorial
  • Quick Reference

4.1 Introduction

Matplotlib may be the most commonly used Python package in two-dimensional graphics. It provides a very fast way to visualize Pyhton data and a number of formatted images that can be released. We need to explore Matplotlib in interactive mode in most common cases.

4.1.1 IPython and Matplotlib Modes

Ipython is an enhanced interactive Python Shell. It has many interesting functions, including naming input and output, accessing Shell commands, improved debugging, and more. It is the core of the scientific computing workflow in Pyhton and is used together with Matplotlib.

For interactive Matplotlib sessions with similar functions of Matlab/Mathematica, we use IPython and its special Matplotlib mode to enable non-blocking plotting.

When Ipython console is used, we start IPython with the command line parameter matplotlib (the-pylab command is used in very old versions)

IPthon notebook in IPthon notebook, we insert the following magic function at the beginning of notebook: % matplotlib inline

4.1.2 pyplot

Pyplot provides a program interface for the matplotlib object-oriented Drawing Library. It is a modeling tool close to Matlab. Therefore, most plot commands in plot have similar Matlab simulation parameters. Important commands are explained using interactive examples.

from matplotlib import pyplot as plt

4.2 simple plotting

In this section, we will plot the cosine and sine functions on the same graph. We will gradually enrich the graph from the default settings to make it better.

Step 1: Obtain the sine and Cosine functions.

import numpy as npX = np.linspace(-np.pi, np.pi, 256, endpoint=True)C, S = np.cos(X), np.sin(X)

X is now a numpy array with 256 values ranging from-π to + π (including), and C is the cosine (256 values ), S is a sine (256 values ).

To run this example, you can type it in IPython interactive session:

$ ipython --pylab

This leads us to the IPython Command Prompt:

IPython 0.13 -- An enhanced Interactive Python.? -> Introduction to IPython's features.%magic -> Information about IPython's 'magic' % functions.help -> Python's own help system.object? -> Details about 'object'. ?object also works, ?? prints more.Welcome to pylab, a matplotlib-based Python environment.For more information, type 'help(pylab)'.

You can also download each example and run it using regular Python commands, but you will lose the interactive data operation.

$ python exercice_1.py

You can click the corresponding graph to obtain the source of each step.

4.2.1 use the default settings for plotting

Documentation

  • Plot tutorial
  • Plot () command
import numpy as npimport matplotlib.pyplot as pltX = np.linspace(-np.pi, np.pi, 256, endpoint=True)C, S = np.cos(X), np.sin(X)plt.plot(X, C)plt.plot(X, S)plt.show()

4.2.2 default instantiation

 

Documentation

  • Customizing matplotlib
import numpy as npimport matplotlib.pyplot as plt# Create a figure of size 8x6 inches, 80 dots per inchplt.figure(figsize=(8, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(1, 1, 1)X = np.linspace(-np.pi, np.pi, 256, endpoint=True)C, S = np.cos(X), np.sin(X)# Plot cosine with a blue continuous line of width 1 (pixels)plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")# Plot sine with a green continuous line of width 1 (pixels)plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")# Set x limitsplt.xlim(-4.0, 4.0)# Set x ticksplt.xticks(np.linspace(-4, 4, 9, endpoint=True))# Set y limitsplt.ylim(-1.0, 1.0)# Set y ticksplt.yticks(np.linspace(-1, 1, 5, endpoint=True))# Save figure using 72 dots per inch# plt.savefig("exercice_2.png", dpi=72)# Show result on screenplt.show()

4.2.3 Change Color and line width

Documentation

  • Controlling line properties
  • Line API

In the first step, we need to set the cosine function to blue, the sine function to red, and set them to a slightly rough line. We will also slightly change the size to make it more horizontal.

...plt.figure(figsize=(10, 6), dpi=80)plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")...

4.2.4 set the limit value

 

Documentation

  • Xlim () command
  • Ylim () command

The current image's limit value is a little compact. We want some space to clearly view all data points.

...plt.xlim(X.min() * 1.1, X.max() * 1.1)plt.ylim(C.min() * 1.1, C.max() * 1.1)...

4.2.5 set the scale value

Documentation

  • Xticks () command
  • Yticks () command
  • Tick container
  • Tick locating and formatting
...plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])plt.yticks([-1, 0, +1])...

 

 

4.2.6 set the scale mark

 

Documentation

  • Working with text
  • Xticks () command
  • Yticks () command
  • Set_xticklabels ()
  • Set_yticklabels ()
...plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])...

 

 

4.2.7 motion spin

 

Documentation

  • Spines
  • Axis container
  • Transformations tutorial
...ax = plt.gca() # gca stands for 'get current axis'ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))...

 

 

4.2.8 Add a legend

 

Documentation

  • Legend guide
  • Legend () command
  • Legend API
...plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")plt.legend(loc='upper left')...

 

4.2.9 notes

Documentation

  • Annotating axis
  • Annotate () command
...t = 2 * np.pi / 3plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")plt.scatter([t, ], [np.cos(t), ], 50, color='blue')plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',xy=(t, np.sin(t)), xycoords='data',xytext=(+10, +30), textcoords='offset points', fontsize=16,arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--")plt.scatter([t, ],[np.sin(t), ], 50, color='red')plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',xy=(t, np.cos(t)), xycoords='data',xytext=(-90, -50), textcoords='offset points', fontsize=16,arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))...

 

4.2.10

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.