Python-matplotlib基本操作

来源:互联网 发布:浙江省纺织品出口数据 编辑:程序博客网 时间:2024/06/08 13:01

废话不多说,直接来干货。
1.用matplotlib画函数图:

import numpy as npfrom matplotlib import pyplot as pltx = np.arange(0, 3 * np.pi,0.1)siny=np.sin(x)cosy=np.cos(x)plt.plot(x,siny,label='sin')plt.plot(x,cosy,label='cos')plt.title('sin and cos')plt.xlabel('xlabel')plt.ylabel('ylabel')plt.legend(loc=4)plt.axis([0,9,-3,3])plt.show()

画函数图

2.画函数图进阶

import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npx = np.arange(0.0,6,0.1)plt.plot(x, [xi**2 for xi in x],label = 'First',linewidth = 4,color = (0,0,0))   plt.plot(x, [xi**2+2 for xi in x],'g',label = 'second')                         plt.plot(x, [xi**2+5 for xi in x],color = (1,0,1,1),label = 'Third')             plt.plot(x, [xi**2+9 for xi in x],color = '#BCD2EE',label = 'Fourth')             plt.axis([0,7,-1,50])plt.xticks(np.arange(0.0,6.0,2.5))plt.xlabel("x",fontsize=15)plt.ylabel(r'y')plt.title('simple plot')plt.legend(loc = 1) #改变图标位置plt.grid(True)plt.savefig('simple plot.jpg',dpi = 200)#print mpl.rcParams['figure.figsize']       #return 8.0,6.0##print mpl.rcParams['savefig.dpi']          #default to 100              the size of the pic will be 800*600plt.show()

进阶

3.画柱状图/饼状图

import matplotlib.pyplot as plt from scipy.misc import imshow,imreadimport numpy as np dict = {'A': 40, 'B': 70, 'C': 30, 'D': 85} plt.figure(figsize=(10,5))plt.subplot(1,2,2)keys=[]values=[]for key in dict:    keys+=[key]    values+=[dict[key]]plt.pie(values,labels=keys,autopct='%0.2f')a=[]plt.subplot(1,2,1)for i, key in enumerate(dict):     plt.bar(i, dict[key])    a+=[dict[key]]plt.xticks(np.arange(len(dict)), dict.keys())plt.yticks(np.array(a))#plt.grid(True)plt.savefig('picture.jpg',dpi=200)I=imread('picture.jpg')imshow(I)plt.show()

柱状图和饼状图

4.饼状图和折线图对比

import matplotlib.pyplot as plt import matplotlib as mplplt.figure(figsize=(15,5));x = [4, 9, 21, 55, 30, 18] labels = ['Swiss', 'Austria', 'Spain', 'Italy', 'France', 'Benelux'] explode = [0.2, 0.1, 0, 0, 0.1, 0] plt.subplot(1,2,1)plt.pie(x,  labels=labels, explode=explode, autopct='%0.2f')plt.subplot(1,2,2)#plt.pie(x,  labels=labels, explode=explode, autopct='%0.2f')plt.plot(x)plt.xticks([0,1,2,3,4,5],[1,2,3,4,5,6])plt.show()

饼状图和折线图

5.散点图

import matplotlib.pyplot as pltimport numpy as npx = np.random.randn(12,20)y = np.random.randn(12,20)mark = ['s','o']for i in range(0,2):    plt.scatter(x[i],y[i],marker = mark[i],color =(np.random.rand(1,3)),s=50,label = str(i+1))    #s是调整点的大小的plt.legend(loc=1)plt.show()

散点图

6.频率分布直方图

import numpy as npfrom matplotlib import pyplot as pltlenths=np.random.randn(1000)def draw_hist(lenths):    plt.figure(figsize=(5,5))    plt.hist(lenths,100)  #第一个参数是数据(列表) ,第二个参数是划分多少块    plt.xlabel('lenth')    plt.xlim(-5,5)    plt.ylabel('Frequency')    plt.title('nomalize')    plt.savefig('normalize.jpg',dpi=200)    plt.show()draw_hist(lenths)

频率分布直方图

7.柱状图和条形图

import matplotlib.pyplot as pltimport numpy as npdef bar_chart_generator():    l=[1,2,3,4,5]    l1 = ['a','b','c','d','e']    h = [20, 14, 38, 27, 9]    w = [0.1, 0.2, 0.3, 0.4, 0.5]    b = [1,2,3,4,5]    plt.subplot(1,2,1)#    for i in l:#        plt.bar(l[i-1], h[i-1],w[i-1],b[i-1])#若循环打印,则各条纹颜色会不同    plt.bar(l, h,w,b,color=(0,0,0))    plt.xticks(l,l1)    plt.subplot(1,2,2)    plt.barh(l,h)    plt.yticks(l,l1)    plt.savefig('bar.png')bar_chart_generator()

柱状图和条形图

8.拟合曲线

import numpy as npimport matplotlib.pyplot as pltx=np.arange(0,20,0.5)y=np.sin(x)plt.scatter(x,y,s=100,color='r',label='sinx')fp2 = np.polyfit(x,y,50)  #生成多项式,阶数自己调f2 = np.poly1d(fp2) #最小二乘法fx = np.arange(0,20,0.1)plt.plot(fx,f2(fx),linewidth=4,color='g',label="curve fitting di=%d"%f2.order)## f2.order: 函数的阶数plt.legend(loc=1)plt.show()

拟合曲线

9.3D图像绘制/3D散点图绘制

from matplotlib import pyplot as pltimport numpy as npfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure()ax = Axes3D(fig)X = np.arange(-4, 4, 0.25)Y = np.arange(-4, 4, 0.25)X, Y = np.meshgrid(X, Y)Z = X**2 + Y**2plt.xlabel('x coordinate')plt.ylabel('y coordinate')plt.title('z=x^2+y^2')# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)ax.plot_surface(X, Y, Z, rstride=1, cstride=1)ax.scatter(X,Y,Z,color='r')plt.savefig('3dpicture.jpg',dpi=200)plt.show()

3D图像

10.画动态图:

from matplotlib import pyplot as pltfrom matplotlib import animationimport numpy as npimport timefrom time import time as timerfig, ax = plt.subplots()plt.axis([0,2,-4,4])line,=ax.plot([],[])t0=timer()def init():    line.set_data([],[])    return linedef animate(i):    x=np.linspace(0,2,100)    y=np.sin(2*np.pi*x)    y1=np.cos(2*np.pi*x)    now= time.strftime("%Y-%m-%d %H:%M:%S")    t1=timer()    plt.title('time:'+now+'cost time='+str(t1-t0))    if i%2==0:        z=y    else:        z=y1    line.set_data(x,z)    return lineanim1=animation.FuncAnimation(fig,animate,init_func=init,interval=5*100)plt.show()

11.显示照片

import matplotlib.pyplot as pltfrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('MNIST_data/')batch_image,batch_label=mnist.train.next_batch(9)fig, axes = plt.subplots(figsize=(12,12), nrows=3, ncols=3)for ax, img in zip(axes.flatten(), batch_image):     ax.axis('off')    ax.imshow(img.reshape((28,28)), cmap='Greys_r')plt.show()

12.matplotlib多子图的添加子标题和主标题的方法

import matplotlib.pyplot as pltimport numpy as npt = np.arange(0,5,0.2)#创建一个数组.arange相当于range,0到5,以0.2作为间隔fig = plt.figure()#figsize=(10,6)#行, 列, 序号ax1 = fig.add_subplot(221) #表示在2*2的网格的格式里,占第一个位置ax2 = fig.add_subplot(222) #表示在2*2的网格的格式里,占第二个位置ax3 = fig.add_subplot(212) #表示在2*1的网格的格式里,占第2个位置#所有图加起来的总大小是定了的#第一个子图里画3条线t,t^2,t^3ax1.plot(t,t,"r--",t,t**2,'b',t,t**3,'g^')ax1.set_title(u'图一plot')#不是子图时,方法是.title,子图时方法是.set_titleax2.semilogy(t,t,"r--",t,t**2,'b',t,t**3,'g^')ax2.set_title(u"图二semilogy")#把y轴取对数ax3.loglog(t,t,"r--",t,t**2,'b',t,t**3,'g^')ax3.set_title(u"图三loglog")#把x,y都取log#大图的标题fig.suptitle('subplot training')#增加子图间的间隔fig.subplots_adjust(hspace=0.4)plt.show()
原创粉丝点击