Matplotlib Simple Drawing

Source: Internet
Author: User
Tags python list

0, Matplotlib--Introduction. Note

Official website:http://matplotlib.org/

1, Matplotlib--draw the polynomial function. Note

#-*-coding:utf-8-*-#绘制多项式函数import numpy as Npimport matplotlib.pyplot as plt# coefficients of the natural number sequence as a polynomial, using the POLYLD function to create the polynomial Func = NP.POLY1D (Np.array ([1,2,3,4]). Astype (float)) print func# creates an x-axis value using NumPy linspace functions, producing 30 evenly spaced values between 10 and 10 x= Np.linspace ( -10,10,30) #计算我们在第一步中创建的多项式的值y =func (x) #调用plot函数, this does not immediately show the function image Plt.plot, x, y # Use the Xlabel function to add the x-axis label Plt.xlabel (' X ') #使用ylabel函数添加y轴的标签plt. Ylabel (' Y (x) ') #调用show函数显示函数图像plt. Show ()



2, Matplotlib--draw the polynomial function and its derivative function. Note

#-*-coding:utf-8-*-#绘制多项式函数及其导函数 # Draw a polynomial function and a guide function using two different styles of curves, and only call the plot function import NumPy as Npimport Matplotlib.pyplot As plt# plots a polynomial, and the first order function func=np.poly1d (Np.array ([1,2,3,4]) obtained using the derive function and the parameter M 1. Astype (float)) Func1=func.deriv (m=1 ) X=np.linspace ( -10,10,30) y=func (x) y1=func1 (x) # Plt.plot (x, y) #多项式函数plt. Plot (x, y, ' ro ', x,y1, ' g--')  # Polynomial functions and first-order derivative functions    red is the derivative, Green is the first-order derivative Plt.xlabel (' x ') Plt.ylabel (' Y ') plt.show ()

3, Matplotlib--draw the polynomial function and its derivative function, first Order guide and second derivative. Note

#-*-Coding:utf-8-*-#绘制多项式函数及其导函数, first derivative and second order import NumPy as Npimport matplotlib.pyplot as plt# create polynomial and its derivative func=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) #使用subplot函数创建第一个子图. # The first parameter of the function is: the number of rows of the child graph # The second parameter of the function is: number of columns of the sub-graph # The third parameter of the function is: Ordinal plt.subplot (311) plt.plot (x, Y, ' R '), starting from 1 ("Ploynomial") # Use the subplot function to create a second sub-graph, using the blue triangle to draw Plt.subplot (312) plt.plot (x,y1, ' b^ ') plt.title ("first derivative") #使用subplot函数绘制第三个子图 , use green circle to draw Plt.subplot (313) Plt.plot (x,y2, ' Go ') plt.title ("Secord derivaive") Plt.xlabel (' x ') Plt.ylabel (' Y ') plt.show ()

4, Matplotlib--draw the stock price throughout the year. Note

#-*-Coding:utf-8-*-#绘制全年的股票价格from matplotlib.dates import dateformatterfrom matplotlib.dates import Daylocatorfrom Matplotlib.dates Import monthlocatorfrom matplotlib.finance import Quotes_historical_yahoofrom matplotlib.finance Import candlestickimport sysfrom datetime import Dateimport Matplotlib.pyplot as Plttoday=date.today () start= ( Today.year-1,today.month,today.day) #将当前的日期减去1年作为起始日期 # Timer Locator, you can locate the month and date on the x-axis alldays=daylocator () months= Monthlocator () #创建一个日期格式化data formatter to format the date on the x-axis. The formatting will create a string containing the abbreviated month and year Month_formatter=dateformatter ("%b%Y") symbol = ' DISH ' #Dish Network Company, DISH stock If Len (sys.argv) = = 2:symbol=sys.argv[1] #从雅虎财经频道下载股价数据quotes =quotes_historical_yahoo (symbol,start,today) Print quotes# Create a Matplotlib figure object, which is the top-level container for the drawing component Fig=plt.figure () #增加一个子图ax =fig.add_subplot (111) #将X轴上的主定位器设置为日定位器. The positioner is responsible for the coarse scale ax.xaxis.set_major_locator (months) #将X轴上的次定位器设置为日定位器 on the x-axis. The locator is responsible for the finer scale ax.xaxis.set_minor_locator (alldays) #将X轴上的主格式化器设置为月格式化器 on the x-axis, which is responsible for the label on the x-axis on the thicker scale ax.xaxis.set_major_ Formatter (MoNth_formatter) #使用获取肚饿股价数据绘制K线图. We can specify the width of the candlestick chart candlestick (ax, quotes) #将X轴上的标签格式化为日期. To better fit the x-axis length, the label will be rotated Fig.autofmt_xdate () plt.show ()

5, Matplotlib--Draw the stock distribution histogram. Note

#-*-Coding:utf-8-*-#绘制股票分布直方图 # Histogram can visualize the distribution of the data # Draw dish the distribution histogram of the stock price from matplotlib.finance import Quotes_historical_ Yahooimport sysfrom datetime import dateimport matplotlib.pyplot as Pltimport numpy as np# download data for the past year Today=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) #上一步得到的股价数据存储在python列表中, converts it into an numpy array and extracts the closing price data Quotes=np.array (quotes) Close =quotes. T[4] #指定合理数量的柱形, plot the distribution histogram plt.hist (Close,np.sqrt (Len (Close)) Plt.show ()

6, Matplotlib--logarithmic axis to draw stock volume. Note

#-*-Coding:utf-8-*-#对数坐标轴 draw stock turnover from matplotlib.dates import dateformatterfrom matplotlib.dates import Daylocatorfro M matplotlib.dates import monthlocatorfrom 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) #将当前的日期减去1年作为起始日期symbol = ' DISH ' #Dish Network company, DISH stock price If Len (sys.argv) = = 2:symbol=sys.argv[1] #从雅虎财经频道下载股 Price Data Quotes=quotes_historical_yahoo (symbol,start,today) print Quotesquotes=np.array (quotes) dates=quotes. T[0]volume=quotes. T[5]alldays=daylocator () Months=monthlocator () month_formatter=dateformatter ("%b%Y") #创建一个Matplotlib的figure对象, This is the top-level container for the drawing component Fig=plt.figure () #增加一个子图ax =fig.add_subplot (111) #使用对数坐标plt. Semilogy (Dates,volume) #将X轴上的主定位器设置为日定位器. The positioner is responsible for the coarse scale ax.xaxis.set_major_locator (months) #将X轴上的次定位器设置为日定位器 on the x-axis. The locator is responsible for the finer scale ax.xaxis.set_minor_locator (alldays) #将X轴上的主格式化器设置为月格式化器 on the x-axis, which is responsible for the label on the x-axis on the thicker scale ax.xaxis.set_major_ Formatter (Month_formatter) #将X轴上的标签格式化为日期.  To better fit the x-axis length, the label will be rotated Fig.autofmt_xdate () plt.show ()

7, Matplotlib--scatter plot chart plot dish stock return rate and volume of scatter plot. Note

#-*-Coding:utf-8-*-#散点图    Draw a scatter chart of dish stock yield and volume 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)    #没有网, this code does not run print quotes# the quotes data obtained is stored in the Python list, Format it as a numpy array and extract the closing price and volume data Quotes=np.array (quotes) close=quotes. T[4]volume=quotes. T[5] #计算股票收益率和成交量的变化值ret =np.diff (Close)/close[:-1]volchange=np.diff (volume)/volume[:-1]# Create a Matplotlib Figure Object Fig=plt.figure () #在图像中绘制一个子图ax =fig.add_subplot (111) #创建散点图 and correlate the color of the data point with the stock yield, The size of the data point is associated with the change in volume Ax.scatter (ret,volchange,c=ret*100,s=volchange*100,alpha=0.5) #设置图像的标题, and the addition of a grid line Ax.set_title (' Close and Volume returns ') Ax.grid (True) plt.show ()

8, Matplotlib--according to the conditions of coloring. Note

#-*-Coding:utf-8-*-#根据条件进行着色 The #fill_between function fills the area of the image with the specified color # The stock graph is shaded and the close price below the mean and above mean is populated with a different color from Matplotlib.finance Import quotes_historical_yahoofrom matplotlib.dates import Dateformatterfrom matplotlib.dates Import daylocatorfrom matplotlib.dates import monthlocatorimport 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) dates=quotes. T[0]close=quotes. T[4]alldays=daylocator () Months=monthlocator () month_formatter=dateformatter ("%b%Y") #创建一个Matplotlib的figure对象fig = Plt.figure () #在图像中添加一个子图ax =fig.add_subplot (111) #绘制收盘价数据ax. Plot (dates,close) #对收盘价下方的数据进行着色, Below or above average close prices are filled with different colors Plt.fill_between (Dates,close.min (), Close,where=close>close.mean (), facecolor= "Green", alpha=0.4) Plt.fill_between (Dates,close.min (), Close,where=close<close.mean (), facecolor= "Red", alpha=0.4) # Set the locator and format the x-axis as a dayPeriod ax.xaxis.set_major_locator (months) ax.xaxis.set_minor_locator (alldays) ax.xaxis.set_major_formatter (month_  Formatter) Ax.grid (True) fig.autofmt_xdate () plt.show ()

9, Matplotlib-use legends and annotations. Note

#-*-Coding:utf-8-*-#使用图例和注释 # Creates a transparent legend with the legend function and automatically determines its placement by matplotlib. You can also use the annotate function to annotate the image accurately, #并有很多可选的注释和箭头风格from matplotlib.finance import Quotes_historical_yahoofrom Matplotlib.dates Import dateformatterfrom matplotlib.dates import daylocatorfrom matplotlib.dates Import Monthlocatorimport 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) dates=quotes. T[0]close=quotes. T[4]fig=plt.figure () Ax=fig.add_subplot (111) #计算并绘制指数移动平均线emas =[]for i in Range (9,18,3): Weights=np.exp (Np.linspace ( -1.,0.,i)) Weights/=weights.sum () ema=np.convolve (Weights,close) [i-1:-i+1] idx= (i-6)/3ax.plot (dates[i-1:],ema,lw= Idx,label= "EMA (%s)"% (i)) Date=np.column_stack ((Dates[i-1:],ema)) Emas.append (Np.rec.fromrecords (date,names=[) Datas "," EMA "])) #找到两条指数移动平均曲线的交点first =emas[0][" EMA "].flaTten () secord=emas[1]["EMA"].flatten () Bools=np.abs (First[-len (Secord):]-secord)/secord<0.0001xpoints= Np.compress (Bools,emas[1]) #将找到的交点用注释和箭头标注出来 and make sure that the annotation text is not far from the intersection for Xpoint in Xpoints:ax.annotate (' X ', Xy=xpoint, Textcoords= ' offset points ', xytext= ( -50,30), Arrowprops=dict (arrowstyle= ")) #添加一个图例并由Matplotlib自动确定其摆放位置leg = Ax.legend (loc= ' best ', fancybox=true) #设置alpha通道值, transparency of the legend Leg.get_frame (). Set_alpha (0.5) alldays=daylocator () months= Monthlocator () month_formatter=dateformatter ("%b%Y") #绘制收盘价数据ax. Plot (dates,close,lw=1.0,label= "close") # The data below the closing price is shaded, below or above the average closing price using a different color fill plt.fill_between (Dates,close.min (), Close,where=close>close.mean (), Facecolor= "Green", alpha=0.4) Plt.fill_between (Dates,close.min (), Close,where=close<close.mean (), facecolor= " Red ", alpha=0.4) #设置定位器并将X轴格式化为日期ax. Xaxis.set_major_locator (months) ax.xaxis.set_minor_locator (alldays) Ax.xaxis.set_major_formatter (Month_formatter) Ax.grid (True) fig.autofmt_xdate () plt.show ()

10, Matplotlib--drawing in 3 dimensional space. Note

#-*-Coding:utf-8-*-#在3维空间中绘图from mpl_toolkits.mplot3d import  axes3dimport matplotlib.pyplot as Pltimport NumPy as Npfrom matplotlib Import cmfig=plt.figure () #使用3d关键字来指定图像的三维投影ax =fig.add_subplot (111,projection= ' 3d ') # Use the Meshgrid function to create a two-dimensional coordinate grid u=np.linspace ( -1,1,100) X,y=np.meshgrid (u,u) z=x**2+y**2# Specify the row and column stride, and the color table used to draw the surface ax.plot_ Surface (x,y,z,rstride=4,cstride=4,cmap=cm. Ylgnbu_r) Plt.show ()

11, Matplotlib--draw a high-level map. Note

#-*-Coding:utf-8-*-#绘制等高图 the Contour 3D drawing in #matplotlib has two styles: filled and non-populated. #我们可以使用contour函数创建一般的等高线图, for contour plots of color fills, you can use Contourfimport Matplotlib.pyplot as Pltimport numpy as Npfrom matplotlib Import cmfig=plt.figure () Ax=fig.add_subplot (111) u=np.linspace ( -1,1,100) X,y=np.meshgrid (u,u) z=x**2+y**2# Draw Contour Map Ax.contourf (x, Y, z) plt.show ()

12, Matplotlib--making animation. Note

#-*-Coding:utf-8-*-#制作动画 # draw 3 randomly generated datasets to display the import NumPy as Npimport Matplotlib.pyplot as pltimport with circles, dots, and triangles, respectively 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) #用不同颜色的圆形, dots, and triangles draw data points from three datasets 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,triangles# use NumPy to generate a random number def generate (): While True:yield Np.random.rand (2,n) anim= Animation. Funcanimation (fig,update,generate,interval=150) plt.show ()

Matplotlib Simple Drawing

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.