Matplotlib tutorial(1)

来源:互联网 发布:淘宝客源码哪个好用 编辑:程序博客网 时间:2024/05/17 03:16

Introduction

matplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quick way to visualize data from Python and publication-quality figures in many formats. We are going to explore matplotlib in interactive mode covering most common cases.

pyplot

pyplot provides a convenient interface(接口) to the matplotlib object-oriented(面向对象) plotting library. It is modeled closely after Matlab(TM). Therefore, the majority of plotting commands in pyplot have Matlab(TM) analogs with similar arguments. Important commands are explained with interactive examples.

Simple Plot

In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default settings, we'll enrich the figure step by step to make it nicer.

First step is to get the data for 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 +π (included). C is the cosine (256 values) and S is the sine (256 values).

Using Defaults

Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You can control the defaults of almost every property in matplotlib:figure size anddpi, line width, color and style,axes, axis andgrid properties,text and font properties and so on. While matplotlib defaults are rather good in most cases, you may want to modify some properties for specific cases.
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()


Instantiating Defaults

In the script below, we've instantiated (and commented) all the figure settings that influence the appearance of the plot. The settings have been explicitly set to their default values, but now you can interactively play with the values to explore their affect.
import numpy as npimport matplotlib.pyplot as plt#create a new figure of size 8*6 points, using 100 dots per inchplt.figure(figsize=(8,6), dpi=80)#create a new subplot from a grid of 1*1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256, endpoint = True)C, S = np.cos(X), np.sin(X)plt.plot(X,C, color=“blue”, linewidth=1.0, linestyle=“-”)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))plt.show()


Changing colors and line widths

First step, we want to have the cosine in blue and the sine in red and a slightly thicker line for both of them. We'll also slightly alter the figure size to make it more horizontal.
plt.plot(X,C, color="blue", linewidth=2.5, linestyle="-")plt.plot(X,S, color="red", linewidth=2.5, linestyle="-")


Setting limits and ticks and tick labels

Current limits of the figure are a bit too tight and we want to make some space in order to clearly see all data points.
plt.ylim(C.min()*1.1, C.max()*1.1)

plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])plt.yticks([-1,0,+1])


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$'])

Moving spines

Spines are the lines connecting the axis tick marks and noting the boundaries of the data area. They can be placed at arbitrary positions and until now, they were on the border of the axis. We'll change that since we want to have them in the middle. Since there are four of them (top/bottom/left/right), we'll discard the top and right by setting their color to none and we'll move the bottom and left ones to coordinate 0 in data space coordinates.
ax = plt.gca()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))


Adding a legend

Let's add a legend in the upper left corner. This only requires adding the keyword argument label (that will be used in the legend box) to the plot commands.
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', frameon = False)


Annotate some points

Let's annotate some interesting points using the annotate command. We chose the 2π/3 value and we want to annotate both the sine and the cosine. We'll first draw a marker on the curve as well as a straight dotted line. Then, we'll use the annotate command to display some text with an arrow.
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"))

Devil is in the details

The tick labels are now hardly visible because of the blue and red lines. We can make them bigger and we can also adjust their properties such that they'll be rendered on a semi-transparent white background. This will allow us to see both the data and the labels.
for label in ax.get_xticklabels() + ax.get_yticklabels():label.set_fontsize(16)label.set_bbox(dict(facecolor='white', edgecolor='None', alpha = 0.65))



1 0
原创粉丝点击