莫烦的python可视化:基于matplotlib.pyplot

 相关的练习:

#coding=gbk
'''
Created on 2018年10月5日
这是来自于视频博主 莫烦的 plt 的基础教学,

@author: Administrator
'''
import matplotlib.pyplot as plt 
import numpy as np
def test_figure(show=False, show_figure1=False, show_figure2=False): 
    X = np.linspace(-3, 3, 50)
    y1 = 2*X + 1
    y2 = X**2
    if show_figure1:
        plt.figure()    #figure函数一下的画图都属于在一幅图中,如果没有,将分开画
        plt.plot(X, y1)
    if show_figure2:
        plt.figure(num=3, figsize=((8, 5)), dpi=100,facecolor='white')#num设置图像号数;图大小
        plt.plot(X, y1)
        plt.plot(X, y2, color='red', linewidth=1.0, linestyle='--')
        
        plt.xlim()   #设置横纵坐标的范围, 此处不能使用 np.linspace(-1, 2,5)
        plt.ylim((-2, 3))
        plt.xlabel('this is X') #设置标签
        plt.ylabel('this is y')
        
        new_ticks = np.linspace(-1, 2,5)    #设置新的横坐标的范围,输入指定的点
        plt.xticks(new_ticks)
        plt.yticks([-2, -1.8, -1, 1.2, 3], 
                   [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']
                   )    #设置对应点的标签
        
        # gca : get current axis
        ax = plt.gca()
        ax.spines['right'].set_color('none') 
        ax.spines['top'].set_color('none')
        ax.xaxis.set_ticks_position('bottom')   #将底部和左边的框设置为X, y轴
        ax.yaxis.set_ticks_position('left')
        ax.spines['bottom'].set_position(('data', 0)) #将x, y的0点,设值为原点
        ax.spines['left'].set_position(('data', 0))
    
    if show:
        plt.show()
# test_figure(True)

def test_legend(show=False, show_figure1=False): 
    X = np.linspace(-3, 3, 50)
    y1 = 2*X + 1
    y2 = X**2
    if show_figure1:
        plt.figure()    #figure函数一下的画图都属于在一幅图中,如果没有,将分开画
        plt.plot(X, y1)
    
    plt.figure(num=3, figsize=((8, 5)), dpi=100,facecolor='white')#num设置图像号数;图大小
#     plt.plot(X, y1)
#     plt.plot(X, y2, color='red', linewidth=1.0, linestyle='--')
    
    plt.xlim()   #设置横纵坐标的范围, 此处不能使用 np.linspace(-1, 2,5)
    plt.ylim((-2, 3))
    plt.xlabel('this is X') #设置标签
    plt.ylabel('this is y')
    
    new_ticks = np.linspace(-1, 2,5)    #设置新的横坐标的范围,输入指定的点
    plt.xticks(new_ticks)
    plt.yticks([-2, -1.8, -1, 1.2, 3], 
               [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']
               )    #设置对应点的标签    
    l1 = plt.plot(X, y2, label='up')    #增加label自定义名字
    l2 = plt.plot(X, y1, label='down', color='blue', linewidth=0.8, linestyle='--')
    plt.legend(loc='lower right') #定义方位, 可以选择   'best'
    
    if show:
        plt.show()
# test_legend(True) 

 plt.legend(loc=1)中loc的常用参数:loc=0 对呀loc='best'

分别为:右上,左上,左下,右下(呈现一个逆时针),还有center right 等

ax.legend(loc=0) # let matplotlib decide the optimal location
ax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner
def test_annotate(show=False):
    plt.figure(num='a')
    X = np.linspace(0, 5, 30)
    y = 2*X + 1
    plt.plot(X, y, color='red')
    ax = plt.gca()
    ax.spines['right'].set_color('none') 
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')   #将底部和左边的框设置为X, y轴
    ax.yaxis.set_ticks_position('left')
    ax.spines['bottom'].set_position(('data', 0)) #将x, y的0点,设值为原点
    ax.spines['left'].set_position(('data', 0))
    
    X0 = 1
    y0 = 2*X0 +1 
    plt.scatter(X0, y0, s=50, color='b')
    plt.plot([X0, X0], [y0, 0], 'k--', linewidth=1.5)
    
    #方法1 
    plt.annotate(r'$2X+1=%s$'%y0, xy=(X0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points',
                 fontsize=16, arrowprops= dict(arrowstyle='->', connectionstyle='arc3, rad=.2')
                 )
    #方法2 
    plt.text(2, 4, r'$This\ is\ some\ text.\ \mu\ \sigma_i\ \alpha_t$', 
             fontdict={'size':10, 'color':'red'}
             )
    if show:
        plt.show()
# test_annotate(True)

 

def test_scatter(show=False): 
    plt.figure(num='test_scatter')
    n = 1024  
    X = np.random.normal(0, 1, n)
    y = np.random.normal(0, 1, n)
    T = np.arctan2(y, X)
    plt.scatter(X, y, s=25, c=T, alpha=0.5) # s 为size, c为color, alpha透明度
    
    plt.xticks(())
    plt.yticks(())  #内置空括号, 不显示坐标
    
    if show:
        plt.show()
# test_scatter(True)
def test_image(show=False):
    a = np.arange(9)
    from sklearn.preprocessing import StandardScaler
    a = StandardScaler().fit_transform(a.reshape(-1,1))
    a = a.reshape(3,3)
    plt.figure(num='test_image')
    
    plt.rcParams['font.sans-serif'] = ['KaiTi']    #显示楷体
    plt.rcParams['axes.unicode_minus'] = False #正常显示负号
    plt.xlabel('显示中文:这是X轴')
    plt.ylabel('显示中文:这是Y轴')
    
    plt.imshow(a, interpolation='nearest', cmap='bone', origin='down')#origin有upper 和 down等
    plt.colorbar(shrink=0.9)    # 旁边的小条显示; 将字体的显示代码放在colorbar前面,解决显示框框的问题
    
    plt.xticks(())
    plt.yticks(())
    if show:
        plt.show()
        
test_image(True)

 

有关于显示中文的参数选项:

方式1:

 plt.rcParams['font.sans-serif'] = ['KaiTi']    #显示楷体
 plt.rcParams['axes.unicode_minus'] = False #正常显示负号

方式2:

该方法较为灵活,只对局部有效。

plt.xlabel('显示中文:这是X轴', fontproperties='SimHei')
plt.ylabel('显示中文:这是Y轴', fontproperties='FangSong')

 

宋体SimSun
黑体SimHei
微软雅黑Microsoft YaHei
微软正黑体Microsoft JhengHei
新宋体NSimSun
新细明体PMingLiU
细明体MingLiU
标楷体DFKai-SB
仿宋FangSong
楷体KaiTi
隶书LiSu
幼圆YouYuan
华文细黑STXihei
华文楷体STKaiti
华文宋体STSong
华文中宋STZhongsong
华文仿宋STFangsong
方正舒体FZShuTi
方正姚体FZYaoti
华文彩云STCaiyun
华文琥珀STHupo
华文隶书STLiti
华文行楷STXingkai
华文新魏STXinwei

 

使用matplotlib 面向对象的方法,只是创建一个局部实例

def test_oob(show=False):
    X = np.linspace(0, 5, 20)
    y = X**2 
    fig = plt.figure(num='api')
    #对轴进行控制
    axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) #参数:  left, bottom, width, height (range 0 to 1)
    axes.plot(X, y, 'r--')
    axes.set_xlabel('X')
    axes.set_ylabel('y')
    axes.set_title('this is title')
    
    #插入一个坐标轴,增加一个图形;主要是方便控制坐标轴
    axes2 = fig.add_axes([0.2, 0.55, 0.4, 0.3])
    axes2.plot(y, X, 'g*-')
    axes2.set_xlabel('x1')
    axes2.set_ylabel('y1')
    axes2.set_title('this is insert_title_1', fontsize=8, color='red')
    if show:
        plt.show()
# test_oob(True)

 

def test_sub(show=False):
    from matplotlib import rcParams
    from math import exp
    rcParams.update({'font.size':10, 'font.family':'serif'})    #对全局的字体大小进行设定,下面自定义字体大小失效
#     rcParams['xtick.major.pad']=5
#     rcParams['ytick.major.pad']=5
    X = np.linspace(0, 5, 20)
    y = X**2
    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10,4))
    axes[0].plot(X, y, label=r'$y\ =\ X^2$')
    axes[0].plot(2*X, y, label=r'$y\ =\ 2\ X\ \alpha^2$')   #支持LaTex 格式,alpha 随意
    axes[0].legend(loc='lower right')
    axes[0].set_title('这是2条线', fontproperties='FangSong')
    
    axes[1].plot(y, X, lw=1, ls='-.', marker='+')
    axes[1].set_xlim([10, 20])  #设置x轴的范围
    axes[1].set_yscale('log')   #设置新的坐标轴刻度
    axes[1].set_ylim()
     
    axes[2].plot(X, X**2)
    axes[2].set_xticks([1,2,3,4,5])
    axes[2].set_xticklabels([r'$\alpha$',r'$\beta$',r'$\gamma$',r'$\delta$',r'$\epsilon$'], fontsize=10)
    yticks = [1, 4, 9, 16, 25]
    axes[2].set_yticks(yticks)
    axes[2].set_yticklabels([r'$%.1f$'%y for y in yticks], fontsize=10) #自定义设置刻度
    axes[2].set_ylabel(r'volumn $(m^2)$', fontsize=10, color='b')
    for label in axes[2].get_yticklabels():
        label.set_color('blue')
#     axes[2].grid(True)    系统自定义参数
    axes[2].grid(color='red', alpha=0.5, linestyle='dashed', linewidth=0.5)
    axes[2].spines['left'].set_color('#99ee88') # 设置y 轴的颜色
    axes[2].spines['bottom'].set_color('k')
    axes[2].spines['bottom'].set_linewidth(2)   #设置x 轴的线宽
    axes[2].spines['right'].set_color('black')
    axes[2].spines['top'].set_color('none')
    
    ax = axes[2].twinx()    #双坐标轴
    ax.plot(X, X**3, lw=2, color='r')
    ax.set_ylabel(r'volumn $(m^3)$', fontsize=10, color='r')
    for label in ax.get_yticklabels():  #将y 轴的刻度值设定为 红色
        label.set_color('red')
    
    fig.tight_layout()
    if show:
        plt.show()
test_sub(True)

def test_2D_plot(show=False):
    n = np.arange(5)
    x = np.random.randn(100)
    fig, axes = plt.subplots(1, 4, figsize=(12, 6))
    
    axes[0].scatter(x, x + 0.25*np.random.randn(len(x)), color='red', s=10)
    axes[0].set_title('scatter')
    
    axes[1].step(n, n**2, lw=2)
    axes[1].set_title('step')
    
    axes[2].bar(n, n**2, align='center', width=0.5, alpha=0.5) 
    axes[2].set_title('bar')
    
    axes[3].fill_between(n, n**2, n**3, color='green', alpha=0.5)   # 在两个区域间进行涂色
    axes[3].set_title('fill_between')
    
    fig2 = plt.figure(num='polar')  # 以极坐标画图
    import math 
    ax = fig2.add_axes([0.2, 0.2, 0.6, 0.6], polar=True)
    s = np.linspace(0 , 2*math.pi, 100)
    ax.plot(s, s, color='red', lw=3)
    
    fig3 = plt.figure(num='subplot')
    fig, ax = plt.subplots(2,3)
    fig.tight_layout()
    
    fig4 = plt.figure(num='plot2grid')
    ax1 = plt.subplot2grid((3,3), (0, 0), colspan=3)
    ax2 = plt.subplot2grid((3,3), (1, 0), colspan=2)
    ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
    ax4 = plt.subplot2grid((3,3), (2, 0))
    ax5 = plt.subplot2grid((3,3), (2, 1))
    
    
    if show:
        plt.show()
test_2D_plot(True)


 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值