Python-matplotlib基本操作

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

import numpy as np
from matplotlib import pyplot as plt
x = 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 mpl

import matplotlib.pyplot as plt

import numpy as np

x = 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*600


plt.show()

进阶

3.画柱状图/饼状图

import matplotlib.pyplot as plt 
from scipy.misc import imshow,imread
import 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 mpl
plt.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 plt

import numpy as np

x = 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 np
from matplotlib import pyplot as plt



lenths=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 plt
import numpy as np

def 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 np
import matplotlib.pyplot as plt
x=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 plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D



fig = 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**2
plt.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 plt
from matplotlib import animation
import numpy as np
import time
from time import time as timer
fig, ax = plt.subplots()
plt.axis([0,2,-4,4])
line,=ax.plot([],[])
t0=timer()
def init():
    line.set_data([],[])
    return line
def 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 line
anim1=animation.FuncAnimation(fig,animate,init_func=init,interval=5*100)
plt.show()

11.显示照片

import matplotlib.pyplot as plt

from tensorflow.examples.tutorials.mnist import input_data

mnist = 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 plt
import numpy as np
t = 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^3
ax1.plot(t,t,"r--",t,t**2,'b',t,t**3,'g^')
ax1.set_title(u'图一plot')#不是子图时,方法是.title,子图时方法是.set_title
ax2.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()
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值