《NumPy Beginner's Guide》笔记Chapter9

来源:互联网 发布:家装软件app 编辑:程序博客网 时间:2024/05/29 09:38
# -*- coding: utf-8 -*-__author__ = 'ZengDong'#日期 =  10:34"""    Matplotlib is a very useful Python plotting library. It integrates nicely withNumPy but is a separate open source project."""import numpy as npimport matplotlib.pyplot as plt"""    1. Simple plots    The matplotlib.pyplot package contains functionality for simple plots. It is important    to remember that each subsequent function call changes the state of the current plot.    function:    poly1d"""#Take the standard input values as polynomial coefficients.  Use the NumPy poly1d functionfunc = np.poly1d(np.array([1, 2, 3, 4]).astype(float))print(func)#create the x value with the Numpy linspace functionx= np.linspace(-10, 10, 30)#calculate the polynomial values using the polynomialy = func(x)#plotplt.plot(x, y)plt.xlabel("X")plt.ylabel("Y")#plt.show()"""    2. Plot format string    The plot function accepts an unlimited number of arguments. In the previous section    we gave it two arrays as arguments. We could also specify the line color and style with an    optional format string. By default, it is a solid blue line denoted as b-, but you can specify a    different color and style such as red dashes.    function:    poly1d    deriv"""#create and differentiate the polynomialfunc = np.poly1d(np.array([1, 2, 3, 4]).astype(float))func1 = func.deriv(m=1)x = np.linspace(-10, 10, 30)y = func(x)y1= func1(x)#plot different styleplt.clf()plt.plot(x, y, "ro", x, y1, "g--")plt.xlabel("X")plt.ylabel("Y")#plt.show()"""    3. Subplots    At a certain point you will have too many lines in one plot. Still, you would like to have    everything grouped together. We can achieve this with the subplot function.    function:    subplot"""#create a polynomial and its derivatives using the following codefunc = np.poly1d(np.array([1, 2, 3, 4]).astype(float))x = np.linspace(-10, 10, 30)y = func(x)func1 = func.deriv(m=1)y1= func1(x)func2 = func.deriv(m=2)y2 = func2(x)#create the first subplot of polynomial with subplot function#The first parameter of this function is the number of rows, the second parameter is the#number of columns, and the third parameter is an index number starting with 1.plt.clf()plt.subplot(311)plt.plot(x, y, "r--")plt.title("Polynomial")plt.subplot(312)plt.plot(x, y1, "b^")plt.title("First Derivative")plt.subplot(313)plt.plot(x, y2, "go")plt.title("Second Derivative")plt.xlabel("X")plt.ylabel("Y")#plt.show()"""    4. Finance    Matplotlib can help us monitor our stock investments. The matplotlib.finance    package has utilities with which we can download stock quotes from Yahoo Finance    function:"""#略过.........."""    5. Histograms    Histograms visualize the distribution of numerical data. Matplotlib has the handy hist    function that graphs histograms. The hist function has two arguments—the array    containing the data and the number of bars.    function:from matplotlib.finance import quotes_historical_yahooimport sysfrom datetime import dateimport matplotlib.pyplot as pltimport numpy as nptoday = date.today()start = (today.year - 1, today.month, today.day)symbol = 'DISH'if len(sys.argv) == 2:    symbol = sys.argv[1]quotes = quotes_historical_yahoo(symbol, start, today)quotes = np.array(quotes)close = quotes.T[4]plt.hist(close, np.sqrt(len(close)))plt.show()""""""    5. Three dimensional plots    Three-dimensional plots are pretty spectacular so we have to cover them here too.    For 3D plots, we need an Axes3D object associated with a 3d projection.    function:"""from mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as pltfrom matplotlib import cmfig = plt.figure()#We need to use the 3d keyword to specify a three-dimensional projection for the plot.ax = fig.add_subplot(111, projection="3d")u = np.linspace(-1, 1, 100)x, y = np.meshgrid(u, u)z = x ** 2 + y ** 2ax.plot_surface(x, y, z, rstride=4, cstride=4, cmap=cm.YlGnBu_r)#plt.show()"""    6. Contour plots    Matplotlib contour 3D plots come in two flavors—filled and unfilled. We can create normal    contour plots with the contour function. For the filled contour plots we can use the    contourf function.    function:"""fig = plt.figure()ax = fig.add_subplot(111)u = np.linspace(-1, 1, 100)x, y = np.meshgrid(u, u)z = x**2 + y**2ax.contourf(x, y, z)plt.show()"""    7. Animation    Matplotlib offers fancy animation capabilities. Matplotlib has a special animation module.    We need to define a callback function that is used to regularly update the screen. We also    need a function to generate data to be plotted.    function:"""import matplotlib.animation as animationfig = plt.figure()ax = fig.add_subplot(111)N = 10x = np.random.rand(N)y = np.random.rand(N)z = np.random.rand(N)#We will plot 3 random datasets as circles, dots and triangles in different colors.circles, triangles, dots = ax.plot(x, 'ro', y, 'g^', z, 'b.')ax.set_ylim(0, 1)plt.axis('off')def update(data):    circles.set_ydata(data[0])    triangles.set_ydata(data[1])    return circles, trianglesdef generate():    while True: yield np.random.rand(2, N)anim = animation.FuncAnimation(fig, update, generate, interval=150)plt.show()
0 0
原创粉丝点击